Esempio n. 1
0
        private void MixedTest(
            PgpPrivateKey pgpPrivKey,
            PgpKey pgpPubKey)
        {
            byte[] text = Encoding.ASCII.GetBytes("hello world!\n");

            MemoryStream bcOut            = new MemoryStream();
            var          messageGenerator = new PgpMessageGenerator(bcOut);

            using (var encryptedGenerator = messageGenerator.CreateEncrypted(PgpSymmetricKeyAlgorithm.Aes128, withIntegrityPacket: true))
            {
                encryptedGenerator.AddMethod(pgpPubKey);
                encryptedGenerator.AddMethod("password", PgpHashAlgorithm.Sha1);
                using (var literalStream = encryptedGenerator.CreateLiteral(PgpDataFormat.Binary, "_CONSOLE", DateTime.UtcNow))
                {
                    literalStream.Write(text);
                }
            }
            byte[] encData = bcOut.ToArray();

            // Asymmetric
            var encryptedMessage = (PgpEncryptedMessage)PgpMessage.ReadMessage(encData);
            var literalMessage   = (PgpLiteralMessage)encryptedMessage.DecryptMessage(pgpPrivKey);

            CheckLiteralData(literalMessage, text);

            // PBE
            encryptedMessage = (PgpEncryptedMessage)PgpMessage.ReadMessage(encData);
            literalMessage   = (PgpLiteralMessage)encryptedMessage.DecryptMessage("password");
            CheckLiteralData(literalMessage, text);
        }
Esempio n. 2
0
        private void doTestTextSig(
            PgpHashAlgorithm hashAlgorithm,
            PgpKey pubKey,
            PgpPrivateKey privKey,
            byte[] data,
            byte[] canonicalData,
            int version = 4)
        {
            MemoryStream bOut             = new MemoryStream();
            var          messageGenerator = new PgpMessageGenerator(bOut);

            using (var signingGenerator = messageGenerator.CreateSigned(PgpSignatureType.CanonicalTextDocument, privKey, PgpHashAlgorithm.Sha1, version))
                using (var literalStream = signingGenerator.CreateLiteral(PgpDataFormat.Text, "_CONSOLE", DateTime.UtcNow))
                {
                    literalStream.Write(data);
                    literalStream.Write(canonicalData);
                }

            /*if (sig.CreationTime == DateTimeOffset.FromUnixTimeSeconds(0).DateTime)
             * {
             *  Fail("creation time not set in v4 signature");
             * }*/

            verifySignature(bOut.ToArray(), hashAlgorithm, pubKey, canonicalData);
        }
Esempio n. 3
0
        private void verifySignature(
            byte[] encodedSig,
            PgpHashAlgorithm hashAlgorithm,
            PgpKey pubKey,
            byte[] original,
            bool checkTime = false)
        {
            var now            = DateTime.UtcNow;
            var signedMessage  = (PgpSignedMessage)PgpMessage.ReadMessage(encodedSig);
            var literalMessage = (PgpLiteralMessage)signedMessage.ReadMessage();

            literalMessage.GetStream().CopyTo(Stream.Null);
            Assert.IsTrue(signedMessage.Verify(pubKey, out DateTime creationTime));
            Assert.IsTrue(!checkTime || Math.Abs((creationTime - now).TotalMinutes) < 10);
            Assert.AreEqual(pubKey.KeyId, signedMessage.KeyId);

            /*
             * sig.InitVerify(pubKey);
             *
             * sig.Update(original);
             * sig.Update(original);
             *
             * if (!sig.Verify())
             * {
             *  Fail("Failed generated signature check against original data");
             * }*/
        }
Esempio n. 4
0
        private void PerformTestSig(
            PgpHashAlgorithm hashAlgorithm,
            PgpKey pubKey,
            PgpPrivateKey privKey)
        {
            const string data = "hello world!";

            byte[]   dataBytes    = Encoding.ASCII.GetBytes(data);
            DateTime testDateTime = new DateTime(1973, 7, 27);

            MemoryStream bOut             = new MemoryStream();
            var          messageGenerator = new PgpMessageGenerator(bOut);

            using (var compressedGenerator = messageGenerator.CreateCompressed(PgpCompressionAlgorithm.Zip))
                using (var signingGenerator = compressedGenerator.CreateSigned(PgpSignatureType.BinaryDocument, privKey, hashAlgorithm))
                    using (var literalStream = signingGenerator.CreateLiteral(PgpDataFormat.Binary, "_CONSOLE", testDateTime))
                    {
                        literalStream.Write(dataBytes);
                    }

            // Verify generated signature
            bOut.Position = 0;
            var compressedMessage = (PgpCompressedMessage)PgpMessage.ReadMessage(bOut);
            var signedMessage     = (PgpSignedMessage)compressedMessage.ReadMessage();
            var literalMessage    = (PgpLiteralMessage)signedMessage.ReadMessage();

            Assert.AreEqual(testDateTime, literalMessage.ModificationTime);
            literalMessage.GetStream().CopyTo(Stream.Null);
            Assert.IsTrue(signedMessage.Verify(pubKey));
        }
Esempio n. 5
0
 private static void ToggleEnableDisableState(Context ctx, PgpKey bob)
 {
     Console.Write("Disable Bob's key.. ");
     bob.Disable(ctx);
     Console.WriteLine("done.");
     Console.Write("Enable Bob's key.. ");
     bob.Enable(ctx);
     Console.WriteLine("done.");
 }
Esempio n. 6
0
 private static void SwitchOwnerTrust(Context ctx, PgpKey bob)
 {
     Console.WriteLine("Set owner trust of Bob's key.");
     Console.Write("\tto never.. ");
     bob.SetOwnerTrust(ctx, PgpOwnerTrust.Never);
     Console.WriteLine("done.");
     Console.Write("\tto ultimate.. ");
     bob.SetOwnerTrust(ctx, PgpOwnerTrust.Ultimate);
     Console.WriteLine("done.");
 }
Esempio n. 7
0
        private static void SetExpirationDate(Context ctx, PgpKey bob)
        {
            DateTime newdate = DateTime.Now.AddYears(5);

            Console.WriteLine("Set new expire date: {0}", newdate);

            PgpExpirationOptions expopts = new PgpExpirationOptions {
                ExpirationDate  = newdate,
                SelectedSubkeys = null // only the primary key
            };

            bob.SetExpirationDate(ctx, expopts);
        }
        private static void PrintUidData(PgpKey key)
        {
            if (key.Uid == null)
            {
                throw new InvalidKeyException();
            }

            Console.WriteLine("{0}'s key {1}\nhas the following Uids and signatures",
                              key.Uid.Name,
                              key.Fingerprint);
            foreach (UserId id in key.Uids)
            {
                Console.WriteLine("\tReal name: {0}\n\t"
                                  + "Email: {1}\n\t"
                                  + "Comment: {2}\n\t"
                                  + "Invalid: {3}\n\t"
                                  + "Revoked: {4}\n\t"
                                  + "Validity: {5}\n\t",
                                  id.Name,
                                  id.Email,
                                  id.Comment,
                                  id.Invalid.ToString(),
                                  id.Revoked.ToString(),
                                  id.Validity.ToString());

                Console.WriteLine("\tSignatures:");
                if (id.Signatures != null)
                {
                    foreach (KeySignature keysig in id.Signatures)
                    {
                        Console.WriteLine("\t\tFrom: {0}\n\t\t"
                                          + "Key id: {1}\n\t\t"
                                          + "Date: {2}\n\t\t"
                                          + "Revoked: {3}\n\t\t"
                                          + "Expires: {4}\n\t\t"
                                          + "Invalid: {5}\n",
                                          keysig.Name,
                                          keysig.KeyId,
                                          keysig.Timestamp.ToString(),
                                          keysig.Revoked.ToString(),
                                          keysig.Expires.ToString(),
                                          keysig.Invalid.ToString());
                    }
                }
                else
                {
                    Console.WriteLine("\t\tNone");
                }
            }
            Console.WriteLine();
        }
        public Key GetKey(string fpr, bool secretOnly)
        {
            if (ctx == null ||
                !(ctx.IsValid))
            {
                throw new InvalidContextException();
            }

            if (fpr == null || fpr.Equals(string.Empty))
            {
                throw new InvalidKeyFprException();
            }

            int    secret  = secretOnly ? 1 : 0;
            IntPtr rkeyPtr = (IntPtr)0;

            lock (ctx.CtxLock)
            {
                // no deadlock because the query is made by the same thread
                Protocol proto = ctx.Protocol;

                gpg_err_code_t errcode = GetKey(fpr, secret, out rkeyPtr);

                if (errcode == gpg_err_code_t.GPG_ERR_NO_ERROR &&
                    !(rkeyPtr.Equals((IntPtr)0)))
                {
                    Key key = null;

                    if (proto == Protocol.OpenPGP)
                    {
                        key = new PgpKey(rkeyPtr);
                    }
                    else if (proto == Protocol.CMS)
                    {
                        key = new X509Key(rkeyPtr);
                    }
                    else
                    {
                        key = new Key(rkeyPtr);
                    }

                    //libgpgme.gpgme_key_release(rkeyPtr);
                    return(key);
                }
                else
                {
                    throw new KeyNotFoundException("The key " + fpr + " could not be found in the keyring.");
                }
            }
        }
Esempio n. 10
0
        private static void ChangePassphrase(Context ctx, PgpKey bob)
        {
            Console.WriteLine("Change the secret key's password.");

            PgpPassphraseOptions passopts = new PgpPassphraseOptions {
                // We need to specify our own passphrase callback methods
                // in case the user does not use gpg-agent.
                OldPassphraseCallback = StaticOldPassphraseCallback,
                NewPassphraseCallback = StaticNewPassphraseCallback,
                // we do not allow an empty passphrase
                EmptyOkay = false
            };

            bob.ChangePassphrase(ctx, passopts);
        }
Esempio n. 11
0
        private static void DisplaySubKeys(PgpKey bob)
        {
            Console.WriteLine("Bob has now the following sub keys:");
            int subkeycount = 0;

            foreach (Subkey subkey in bob.Subkeys)
            {
                subkeycount++;
                Console.WriteLine("{0}\n\tAlgorithm: {1}\n\t"
                                  + "Length: {2}\n\t"
                                  + "Expires: {3}\n",
                                  subkey.Fingerprint,
                                  Gpgme.GetPubkeyAlgoName(subkey.PubkeyAlgorithm),
                                  subkey.Length.ToString(CultureInfo.InvariantCulture),
                                  subkey.Expires.ToString(CultureInfo.InvariantCulture));
            }
            Console.WriteLine("Found {0} sub keys.", subkeycount.ToString(CultureInfo.InvariantCulture));
        }
Esempio n. 12
0
        private void doTestSig(
            PgpHashAlgorithm hashAlgorithm,
            PgpKey pubKey,
            PgpPrivateKey privKey,
            int version = 4)
        {
            MemoryStream bOut = new MemoryStream();

            var messageGenerator = new PgpMessageGenerator(bOut);

            using (var signingGenerator = messageGenerator.CreateSigned(PgpSignatureType.BinaryDocument, privKey, hashAlgorithm, version))
                using (var literalStream = signingGenerator.CreateLiteral(PgpDataFormat.Binary, "_CONSOLE", DateTime.UtcNow))
                {
                    literalStream.Write(TEST_DATA);
                    literalStream.Write(TEST_DATA);
                }

            verifySignature(bOut.ToArray(), hashAlgorithm, pubKey, TEST_DATA);
        }
Esempio n. 13
0
        public static void SignAndVerifyTestMessage(PgpPrivateKey privateKey, PgpKey publicKey)
        {
            byte[] msg           = Encoding.ASCII.GetBytes("hello world!");
            var    encodedStream = new MemoryStream();

            var messageGenerator = new PgpMessageGenerator(encodedStream);

            using (var signedGenerator = messageGenerator.CreateSigned(PgpSignatureType.BinaryDocument, privateKey, PgpHashAlgorithm.Sha256))
                using (var literalStream = signedGenerator.CreateLiteral(PgpDataFormat.Binary, "", DateTime.UtcNow))
                {
                    literalStream.Write(msg);
                }

            encodedStream.Position = 0;
            var signedMessage  = (PgpSignedMessage)PgpMessage.ReadMessage(encodedStream);
            var literalMessage = (PgpLiteralMessage)signedMessage.ReadMessage();

            // Skip over literal data
            literalMessage.GetStream().CopyTo(Stream.Null);
            Assert.IsTrue(signedMessage.Verify(publicKey));
        }
Esempio n. 14
0
        public void Encrypt()
        {
            PgpKey pKey = (PgpKey)keys[0];

            UTF8Encoding utf8       = new UTF8Encoding();
            string       secrettext = System.IO.File.ReadAllText(Source);

            plain.FileName = Source;
            BinaryWriter binwriter = new BinaryWriter(plain, utf8);

            binwriter.Write(secrettext.ToCharArray());
            binwriter.Flush();

            binwriter.Seek(0, SeekOrigin.Begin);

            ctx.Armor = true;
            GpgmeData cipher = new GpgmeFileData(Destination, FileMode.Create, FileAccess.ReadWrite);

            cipher.FileName = Destination;
            var result = ctx.Encrypt(new Key[] { pKey }, EncryptFlags.AlwaysTrust, plain, cipher);

            cipher.Close();
        }
Esempio n. 15
0
        private static void AddSubKey(Context ctx, PgpKey bob)
        {
            Console.Write("Add a new subkey to Bob's key.. ");

            /* Set the password callback - needed if the user doesn't run
             * gpg-agent or any other password / pin-entry software.
             */
            ctx.SetPassphraseFunction(StaticOldPassphraseCallback);

            PgpSubkeyOptions subopts = new PgpSubkeyOptions {
                /* Same as:
                 * subopts.SetAlgorithm(KeyAlgorithm.RSA);
                 * subopts.Capability = AlgorithmCapability.CanEncrypt;
                 */
                Algorithm      = PgpSubkeyAlgorithm.RSAEncryptOnly,
                KeyLength      = PgpSubkeyOptions.KEY_LENGTH_4096,
                ExpirationDate = DateTime.Now.AddDays(90)
            };

            bob.AddSubkey(ctx, subopts);

            Console.WriteLine("Done.");
        }
        static void Main(string[] args)
        {
            Context ctx = new Context();

            if (ctx.Protocol != Protocol.OpenPGP)
            {
                ctx.SetEngineInfo(Protocol.OpenPGP, null, null);
            }

            Console.WriteLine("Search Bob's PGP key in the default keyring..");

            String    searchstr = "*****@*****.**";
            IKeyStore keyring   = ctx.KeyStore;

            // retrieve all keys that have Bob's email address
            Key[] keys = keyring.GetKeyList(searchstr, false);
            if (keys == null || keys.Length == 0)
            {
                Console.WriteLine("Cannot find Bob's PGP key {0} in your keyring.", searchstr);
                Console.WriteLine("You may want to create the PGP key by using the appropriate\n"
                                  + "sample in the Samples/ directory.");
                return;
            }

            // print a list of all returned keys
            foreach (Key key in keys)
            {
                if (key.Uid != null &&
                    key.Fingerprint != null)
                {
                    Console.WriteLine("Found key {0} with fingerprint {1}",
                                      key.Uid.Name,
                                      key.Fingerprint);
                }
            }

            // we are going to use the first key in the list
            PgpKey bob = (PgpKey)keys[0];

            if (bob.Uid == null || bob.Fingerprint == null)
            {
                throw new InvalidKeyException();
            }

            // Create a sample string
            StringBuilder randomtext = new StringBuilder();

            for (int i = 0; i < 80 * 6; i++)
            {
                randomtext.Append((char)(34 + i % 221));
            }
            string secrettext = new string('+', 508)
                                + " Die Gedanken sind frei "
                                + new string('+', 508)
                                + randomtext.ToString();

            Console.WriteLine("Text to be encrypted:\n\n{0}", secrettext);

            // we want our string UTF8 encoded.
            UTF8Encoding utf8 = new UTF8Encoding();

            // create a (dynamic) memory based data buffer to place the unencrypted (plain) text
            GpgmeData plain = new GpgmeMemoryData();

            // set a filename for this data buffer
            plain.FileName = "my_document.txt";

            BinaryWriter binwriter = new BinaryWriter(plain, utf8);

            // write our secret text to the memory buffer
            binwriter.Write(secrettext.ToCharArray());
            binwriter.Flush();
            // go to the beginning(!)
            binwriter.Seek(0, SeekOrigin.Begin);

            /////// ENCRYPT DATA ///////

            // we want or PGP encrypted data RADIX/BASE64 encoded.
            ctx.Armor = true;

            // create another (dynamic) memory based data buffer as destination
            GpgmeData cipher = new GpgmeMemoryData();

            cipher.FileName = "my_document.txt";

            Console.Write("Encrypt data for {0} ({1}).. ",
                          bob.Uid.Name, bob.KeyId);

            EncryptionResult encrst = ctx.Encrypt(
                new Key[] { bob },        // encrypt data to Bob's key only
                EncryptFlags.AlwaysTrust, // trust our sample PGP key
                plain,                    // source buffer
                cipher);                  // destination buffer

            Console.WriteLine("done.");
            Console.WriteLine("Cipher text:");

            // move cursor to the beginning
            cipher.Seek(0, SeekOrigin.Begin);

            /* Read cipher text from libgpgme's memory based buffer and print
             * it to the console screen.
             */
            char[] buf;
            // the cipher text is UTF8 encoded
            BinaryReader binreader = new BinaryReader(cipher, utf8);

            while (true)
            {
                try
                {
                    buf = binreader.ReadChars(255);
                    if (buf.Length == 0)
                    {
                        break;
                    }
                    Console.Write(buf);
                }
                catch (EndOfStreamException)
                {
                    break;
                }
            }

            /////// DECRYPT DATA ///////

            /* Set the password callback - needed if the user doesn't run
             * gpg-agent or any other password / pin-entry software.
             */
            ctx.SetPassphraseFunction(new PassphraseDelegate(MyPassphraseCallback));

            // go to the beginning(!)
            cipher.Seek(0, SeekOrigin.Begin);

            Console.Write("Decrypt data.. ");
            GpgmeData decryptedText = new GpgmeMemoryData();

            DecryptionResult decrst = ctx.Decrypt(
                cipher,         // source buffer
                decryptedText); // destination buffer

            Console.WriteLine("Done. Filename: \"{0}\" Recipients:",
                              decrst.FileName);

            /* print out all recipients key ids (a PGP package can be
             * encrypted to various recipients).
             */
            if (decrst.Recipients != null)
            {
                foreach (Recipient recp in decrst.Recipients)
                {
                    Console.WriteLine("\tKey id {0} with {1} algorithm",
                                      recp.KeyId,
                                      Gpgme.GetPubkeyAlgoName(recp.KeyAlgorithm));
                }
            }
            else
            {
                Console.WriteLine("\tNone");
            }

            // TEST: Compare original data and decrypted data
            byte[] orig = new byte[255], cmp = new byte[255];

            plain.Seek(0, SeekOrigin.Begin);
            decryptedText.Seek(0, SeekOrigin.Begin);

            while (true)
            {
                try
                {
                    int a, b;
                    a = plain.Read(orig, orig.Length);
                    b = decryptedText.Read(cmp, cmp.Length);

                    if (a != b)
                    {
                        throw new DecryptionFailedException("The two data buffers have different sizes.");
                    }

                    if (a == 0)
                    {
                        break; // everything okay - end of stream reached.
                    }
                    for (int i = 0; i < a; i++)
                    {
                        if (orig[i] != cmp[i])
                        {
                            throw new DecryptionFailedException("The two data buffers differ at position "
                                                                + i.ToString() + ".");
                        }
                    }
                }
                catch (EndOfStreamException)
                {
                    throw new DecryptionFailedException("The two data buffers have different sizes.");
                }
            }

            // we do not want our GpgmeData buffers destroyed
            GC.KeepAlive(binwriter);
            GC.KeepAlive(binreader);

            /////// FILE BASED DATA BUFFERS ///////

            /////// ENCRYPT FILE ///////

            // Now let's use a file based data buffers

            // create the "source" file first and fill it with our sample text.
            Console.WriteLine("Create new file plainfile.txt.");
            File.WriteAllText("plainfile.txt", secrettext, utf8);

            GpgmeData plainfile = new GpgmeFileData(
                "plainfile.txt",
                FileMode.Open,
                FileAccess.Read);

            GpgmeData cipherfile = new GpgmeFileData(
                "cipherfile.asc",
                FileMode.Create,
                FileAccess.ReadWrite);

            Console.Write("Encrypt file plainfile.txt to cipherfile.asc.. ");

            encrst = ctx.Encrypt(
                new Key[] { bob },
                EncryptFlags.AlwaysTrust,
                plainfile,
                cipherfile);

            Console.WriteLine("done.");

            plainfile.Close();
            cipherfile.Close();

            /////// DECRYPT FILE ///////

            //cipherfile = new GpgmeFileData("cipherfile.asc");
            // load the file content into the system memory
            cipherfile = new GpgmeMemoryData("cipherfile.asc");

            plainfile = new GpgmeFileData(
                "decrypted.txt",
                FileMode.Create,
                FileAccess.Write);

            Console.WriteLine("Decrypt file cipherfile.asc to decrypted.txt.. ");

            decrst = ctx.Decrypt(
                cipherfile,     // source buffer
                plainfile);     // destination buffer

            Console.WriteLine("Done. Filename: \"{0}\" Recipients:",
                              decrst.FileName);

            /* print out all recipients key ids (a PGP package can be
             * encrypted to various recipients).
             */
            if (decrst.Recipients != null)
            {
                foreach (Recipient recp in decrst.Recipients)
                {
                    Console.WriteLine("\tKey id {0} with {1} algorithm",
                                      recp.KeyId,
                                      Gpgme.GetPubkeyAlgoName(recp.KeyAlgorithm));
                }
            }
            else
            {
                Console.WriteLine("\tNone");
            }

            cipherfile.Close();
            plainfile.Close();

            return;
        }
        static void Main(string[] args)
        {
            Context ctx = new Context();

            if (ctx.Protocol != Protocol.OpenPGP)
            {
                ctx.SetEngineInfo(Protocol.OpenPGP, null, null);
            }

            Console.WriteLine("Search Bob's and Alice's PGP keys in the default keyring..");

            String[] searchpattern = new string[] {
                "*****@*****.**",
                "*****@*****.**"
            };

            IKeyStore keyring = ctx.KeyStore;

            /* Enable the listing of signatures. By default
             * key signatures are NOT passed.
             */
            ctx.KeylistMode = KeylistMode.Signatures;

            // retrieve all keys that have Bob's or Alice's email address
            Key[] keys = keyring.GetKeyList(searchpattern, false);

            PgpKey bob = null, alice = null;

            if (keys != null && keys.Length != 0)
            {
                foreach (Key k in keys)
                {
                    if (k.Uid != null)
                    {
                        if (bob == null && k.Uid.Email.ToLower().Equals("*****@*****.**"))
                        {
                            bob = (PgpKey)k;
                        }
                        if (alice == null && k.Uid.Email.ToLower().Equals("*****@*****.**"))
                        {
                            alice = (PgpKey)k;
                        }
                    }
                    else
                    {
                        throw new InvalidKeyException();
                    }
                }
            }

            if (bob == null || alice == null)
            {
                Console.WriteLine("Cannot find Bob's or Alice's PGP key in your keyring.");
                Console.WriteLine("You may want to create the PGP key by using the appropriate\n"
                                  + "sample in the Samples/ directory.");
                return;
            }

            // Print out all Uids from Bob's key
            PrintUidData(bob);

            // Print out all Uids from Alice's key
            PrintUidData(alice);


            Console.WriteLine("Set Alice's PGP key as signer key.");
            // Clear signer list (remove default key)
            ctx.Signers.Clear();
            // Add Alice's key as signer
            ctx.Signers.Add(alice);

            /* Set the password callback - needed if the user doesn't run
             * gpg-agent or any other password / pin-entry software.
             */
            ctx.SetPassphraseFunction(new PassphraseDelegate(MyPassphraseCallback));

            Console.WriteLine("Sign Bob's PGP key with Alice's key.. ");

            /////// SIGN KEY ///////

            PgpSignatureOptions signopts = new PgpSignatureOptions();

            signopts.SelectedUids = new int[] { 1 }; // sign the latest Uid only!
            signopts.TrustLevel   = PgpSignatureTrustLevel.Full;
            signopts.Type         = PgpSignatureType.Trust | PgpSignatureType.NonExportable;

            try
            {
                bob.Sign(ctx, signopts);
            }
            catch (AlreadySignedException)
            {
                Console.WriteLine("Bob's key is already signed!");
            }
            catch (Exception ex)
            {
                throw ex;
            }

            // Refresh Bob's key
            bob = (PgpKey)keyring.GetKey(bob.Fingerprint, false);

            PrintUidData(bob);

            /////// REVOKE SIGNATURE ///////

            Console.WriteLine("Revoke the signature..");

            // We need to find Alice's signature first
            int nsignature = 0;

            foreach (KeySignature keysig in bob.Uid.Signatures)
            {
                if (!keysig.Revoked)
                {
                    nsignature++; // do not count revocation certificates
                }
                if (keysig.KeyId.Equals(alice.KeyId) &&
                    !keysig.Revoked) // must not be a revocation certificate
                {
                    break;           // found!
                }
            }

            PgpRevokeSignatureOptions revopts = new PgpRevokeSignatureOptions();

            revopts.SelectedUid        = 1; // latest uid
            revopts.SelectedSignatures = new int[] { nsignature };
            revopts.ReasonText         = "Test revocation";

            bob.RevokeSignature(ctx, revopts);

            // Refresh Bob's key
            bob = (PgpKey)keyring.GetKey(bob.Fingerprint, false);

            PrintUidData(bob);

            /////// DELETE SIGNATURE ///////

            Console.WriteLine("Remove Alice's signature and revocation certificate(s)..");

            List <int> siglst = new List <int>();

            nsignature = 0;
            foreach (KeySignature keysig in bob.Uid.Signatures)
            {
                nsignature++;
                if (keysig.KeyId.Equals(alice.KeyId))
                {
                    siglst.Add(nsignature);
                }
            }

            PgpDeleteSignatureOptions delsigopts = new PgpDeleteSignatureOptions();

            delsigopts.DeleteSelfSignature = false;
            delsigopts.SelectedUid         = 1;
            delsigopts.SelectedSignatures  = siglst.ToArray();

            bob.DeleteSignature(ctx, delsigopts);

            // Refresh Bob's key
            bob = (PgpKey)keyring.GetKey(bob.Fingerprint, false);

            PrintUidData(bob);

            return;
        }
Esempio n. 18
0
        static void Main()
        {
            Context ctx = new Context();

            if (ctx.Protocol != Protocol.OpenPGP)
            {
                ctx.SetEngineInfo(Protocol.OpenPGP, null, null);
            }

            Console.WriteLine("Search Bob's and Alice's PGP keys in the default keyring..");

            String[] searchpattern = new[] {
                "*****@*****.**",
                "*****@*****.**"
            };

            IKeyStore keyring = ctx.KeyStore;

            // We want the key signatures!
            ctx.KeylistMode = KeylistMode.Signatures;

            // retrieve all keys that have Bob's or Alice's email address
            Key[] keys = keyring.GetKeyList(searchpattern, false);

            PgpKey bob = null, alice = null;

            if (keys != null && keys.Length != 0)
            {
                foreach (Key k in keys)
                {
                    if (k.Uid != null)
                    {
                        if (bob == null && k.Uid.Email.ToLower().Equals("*****@*****.**"))
                        {
                            bob = (PgpKey)k;
                        }
                        if (alice == null && k.Uid.Email.ToLower().Equals("*****@*****.**"))
                        {
                            alice = (PgpKey)k;
                        }
                    }
                    else
                    {
                        throw new InvalidKeyException();
                    }
                }
            }

            if (bob == null || alice == null)
            {
                Console.WriteLine("Cannot find Bob's or Alice's PGP key in your keyring.");
                Console.WriteLine("You may want to create the PGP keys by using the appropriate\n"
                                  + "sample in the Samples/ directory.");
                return;
            }

            // Create a sample string
            StringBuilder randomtext = new StringBuilder();

            for (int i = 0; i < 80 * 6; i++)
            {
                randomtext.Append((char)(34 + i % 221));
            }
            string origintxt         = new string('+', 508)
                                       + " Die Gedanken sind frei "
                                       + new string('+', 508)
                                       + randomtext;

            // we want our string UTF8 encoded.
            UTF8Encoding utf8 = new UTF8Encoding();

            // Write sample string to plain.txt
            File.WriteAllText("plain.txt", origintxt, utf8);

            /////// ENCRYPT AND SIGN DATA ///////

            Console.Write("Encrypt data for Bob and sign it with Alice's PGP key.. ");

            GpgmeData plain  = new GpgmeFileData("plain.txt");
            GpgmeData cipher = new GpgmeFileData("cipher.asc");

            // we want or PGP encrypted/signed data RADIX/BASE64 encoded.
            ctx.Armor = true;

            /* Set the password callback - needed if the user doesn't run
             * gpg-agent or any other password / pin-entry software.
             */
            ctx.SetPassphraseFunction(MyPassphraseCallback);

            // Set Alice's PGP key as signer
            ctx.Signers.Clear();
            ctx.Signers.Add(alice);

            EncryptionResult encrst = ctx.EncryptAndSign(
                new Key[] { bob },
                EncryptFlags.AlwaysTrust,
                plain,
                cipher);

            Console.WriteLine("done.");

            // print out invalid signature keys
            if (encrst.InvalidRecipients != null)
            {
                foreach (InvalidKey key in encrst.InvalidRecipients)
                {
                    Console.WriteLine("Invalid key: {0} ({1})",
                                      key.Fingerprint,
                                      key.Reason);
                }
            }

            plain.Close();
            cipher.Close();

            /////// DECRYPT AND VERIFY DATA ///////

            Console.Write("Decrypt and verify data.. ");

            cipher = new GpgmeFileData("cipher.asc");
            plain  = new GpgmeMemoryData();

            CombinedResult comrst = ctx.DecryptAndVerify(
                cipher, // source buffer
                plain); // destination buffer

            Console.WriteLine("Done. Filename: \"{0}\" Recipients:",
                              comrst.DecryptionResult.FileName);

            /* print out all recipients key ids (a PGP package can be
             * encrypted to various recipients).
             */
            DecryptionResult decrst = comrst.DecryptionResult;

            if (decrst.Recipients != null)
            {
                foreach (Recipient recp in decrst.Recipients)
                {
                    Console.WriteLine("\tKey id {0} with {1} algorithm",
                                      recp.KeyId,
                                      Gpgme.GetPubkeyAlgoName(recp.KeyAlgorithm));
                }
            }
            else
            {
                Console.WriteLine("\tNone");
            }

            // print out signature information
            VerificationResult verrst = comrst.VerificationResult;

            if (verrst.Signature != null)
            {
                foreach (Signature sig in verrst.Signature)
                {
                    Console.WriteLine("Verification result (signature): "
                                      + "\n\tFingerprint: {0}"
                                      + "\n\tHash algorithm: {1}"
                                      + "\n\tKey algorithm: {2}"
                                      + "\n\tTimestamp: {3}"
                                      + "\n\tSummary: {4}"
                                      + "\n\tValidity: {5}",
                                      sig.Fingerprint,
                                      Gpgme.GetHashAlgoName(sig.HashAlgorithm),
                                      Gpgme.GetPubkeyAlgoName(sig.PubkeyAlgorithm),
                                      sig.Timestamp,
                                      sig.Summary,
                                      sig.Validity);
                }
            }
        }
        static void Main(string[] args)
        {
            Context ctx = new Context();

            if (ctx.Protocol != Protocol.OpenPGP)
            {
                ctx.SetEngineInfo(Protocol.OpenPGP, null, null);
            }

            Console.WriteLine("Search Bob's PGP key in the default keyring..");

            String    searchstr = "*****@*****.**";
            IKeyStore keyring   = ctx.KeyStore;

            // retrieve all keys that have Bob's email address
            Key[] keys = keyring.GetKeyList(searchstr, false);
            if (keys == null || keys.Length == 0)
            {
                Console.WriteLine("Cannot find Bob's PGP key {0} in your keyring.", searchstr);
                Console.WriteLine("You may want to create the PGP key by using the appropriate\n"
                                  + "sample in the Samples/ directory.");
                return;
            }

            // print a list of all returned keys
            foreach (Key key in keys)
            {
                if (key.Uid != null &&
                    key.Fingerprint != null)
                {
                    Console.WriteLine("Found key {0} with fingerprint {1}",
                                      key.Uid.Name,
                                      key.Fingerprint);
                }
            }

            // we are going to use the first key in the list
            PgpKey bob = (PgpKey)keys[0];

            if (bob.Uid == null || bob.Fingerprint == null)
            {
                throw new InvalidKeyException();
            }

            Console.WriteLine("\nUsing key {0}", bob.Fingerprint);

            /////// CHANGE PASSPHRASE ///////

            Console.WriteLine("Change the secret key's password.");

            PgpPassphraseOptions passopts = new PgpPassphraseOptions();

            /* We need to specify our own passphrase callback methods
             * in case the user does not use gpg-agent.
             */
            passopts.OldPassphraseCallback = new PassphraseDelegate(MyPassphraseCallback);
            passopts.NewPassphraseCallback = new PassphraseDelegate(MyNewPassphraseCallback);
            passopts.EmptyOkay             = false; // we do not allow an empty passphrase

            bob.ChangePassphrase(ctx, passopts);

            /////// ADD SUBKEY ///////

            Console.Write("Add a new subkey to Bob's key.. ");

            /* Set the password callback - needed if the user doesn't run
             * gpg-agent or any other password / pin-entry software.
             */
            ctx.SetPassphraseFunction(new PassphraseDelegate(MyPassphraseCallback));

            PgpSubkeyOptions subopts = new PgpSubkeyOptions();

            subopts.Algorithm = PgpSubkeyAlgorithm.RSAEncryptOnly;

            /* Same as:
             * subopts.SetAlgorithm(KeyAlgorithm.RSA);
             * subopts.Capability = AlgorithmCapability.CanEncrypt;
             */
            subopts.KeyLength      = PgpSubkeyOptions.KEY_LENGTH_4096;
            subopts.ExpirationDate = DateTime.Now.AddDays(90);

            bob.AddSubkey(ctx, subopts);

            Console.WriteLine("Done.");

            /////// VIEW SUBKEYS ///////

            // Reload Bobs key
            bob = (PgpKey)keyring.GetKey(bob.Fingerprint, false);

            Console.WriteLine("Bob has now the following sub keys:");
            int subkeycount = 0;

            foreach (Subkey subkey in bob.Subkeys)
            {
                subkeycount++;
                Console.WriteLine("{0}\n\tAlgorithm: {1}\n\t"
                                  + "Length: {2}\n\t"
                                  + "Expires: {3}\n",
                                  subkey.Fingerprint,
                                  Gpgme.GetPubkeyAlgoName(subkey.PubkeyAlgorithm),
                                  subkey.Length.ToString(),
                                  subkey.Expires.ToString());
            }
            Console.WriteLine("Found {0} sub keys.", subkeycount.ToString());

            /////// SET OWNER TRUST ///////
            Console.WriteLine("Set owner trust of Bob's key.");
            Console.Write("\tto never.. ");
            bob.SetOwnerTrust(ctx, PgpOwnerTrust.Never);
            Console.WriteLine("done.");
            Console.Write("\tto ultimate.. ");
            bob.SetOwnerTrust(ctx, PgpOwnerTrust.Ultimate);
            Console.WriteLine("done.");

            /////// ENABLE / DISABLE ///////
            Console.Write("Disable Bob's key.. ");
            bob.Disable(ctx);
            Console.WriteLine("done.");
            Console.Write("Enable Bob's key.. ");
            bob.Enable(ctx);
            Console.WriteLine("done.");

            /////// SET EXPIRE DATE ///////
            DateTime newdate = DateTime.Now.AddYears(5);

            Console.WriteLine("Set new expire date: {0}", newdate);

            PgpExpirationOptions expopts = new PgpExpirationOptions();

            expopts.ExpirationDate  = newdate;
            expopts.SelectedSubkeys = null; // only the primary key
            bob.SetExpirationDate(ctx, expopts);

            return;
        }
Esempio n. 20
0
        static void Main()
        {
            Context ctx = new Context();

            if (ctx.Protocol != Protocol.OpenPGP)
            {
                ctx.SetEngineInfo(Protocol.OpenPGP, null, null);
            }

            Console.WriteLine("Search Alice's PGP key in the default keyring..");

            const string SEARCHSTR = "*****@*****.**";
            IKeyStore    keyring   = ctx.KeyStore;

            // retrieve all keys that have Alice's email address
            Key[] keys = keyring.GetKeyList(SEARCHSTR, false);
            if (keys == null || keys.Length == 0)
            {
                Console.WriteLine("Cannot find Alice's PGP key {0} in your keyring.", SEARCHSTR);
                Console.WriteLine("You may want to create the PGP key by using the appropriate\n"
                                  + "sample in the Samples/ directory.");
                return;
            }

            // print a list of all returned keys
            foreach (Key key in keys)
            {
                if (key.Uid != null && key.Fingerprint != null)
                {
                    Console.WriteLine("Found key {0} with fingerprint {1}",
                                      key.Uid.Name,
                                      key.Fingerprint);
                }
            }

            // we are going to use the first key in the list
            PgpKey alice = (PgpKey)keys[0];

            if (alice.Uid == null || alice.Fingerprint == null)
            {
                throw new InvalidKeyException();
            }

            // Create a sample string
            StringBuilder randomtext = new StringBuilder();

            for (int i = 0; i < 80 * 6; i++)
            {
                randomtext.Append((char)(34 + i % 221));
            }
            string origintxt = new string('+', 508)
                               + " Die Gedanken sind frei "
                               + new string('+', 508)
                               + randomtext;

            Console.WriteLine("Text to be signed:\n\n{0}", origintxt);

            // we want our string UTF8 encoded.
            UTF8Encoding utf8 = new UTF8Encoding();

            // Prepare a file for later usage
            File.WriteAllText("original.txt", origintxt, utf8);

            /////// SIGN DATA (detached signature) ///////

            Console.Write("Write a detached signature to file: original.txt.sig.. ");

            GpgmeData origin = new GpgmeFileData("original.txt",
                                                 FileMode.Open,
                                                 FileAccess.Read);

            GpgmeData detachsig = new GpgmeFileData("original.txt.sig",
                                                    FileMode.Create,
                                                    FileAccess.Write);

            // Set Alice as signer
            ctx.Signers.Clear();
            ctx.Signers.Add(alice);

            // we want or PGP encrypted/signed data RADIX/BASE64 encoded.
            ctx.Armor = true;

            /* Set the password callback - needed if the user doesn't run
             * gpg-agent or any other password / pin-entry software.
             */
            ctx.SetPassphraseFunction(MyPassphraseCallback);

            // create a detached signature
            SignatureResult sigrst = ctx.Sign(
                origin,     // plain text (source buffer)
                detachsig,  // signature (destination buffer)
                SignatureMode.Detach);

            Console.WriteLine("done.");

            // print out invalid signature keys
            if (sigrst.InvalidSigners != null)
            {
                foreach (InvalidKey key in sigrst.InvalidSigners)
                {
                    Console.WriteLine("Invalid key: {0} ({1})",
                                      key.Fingerprint,
                                      key.Reason);
                }
            }

            // print out signature information
            if (sigrst.Signatures != null)
            {
                foreach (NewSignature newsig in sigrst.Signatures)
                {
                    Console.WriteLine("New signature: "
                                      + "\n\tFingerprint: {0}"
                                      + "\n\tHash algorithm: {1}"
                                      + "\n\tKey algorithm: {2}"
                                      + "\n\tTimestamp: {3}"
                                      + "\n\tType: {4}",
                                      newsig.Fingerprint,
                                      Gpgme.GetHashAlgoName(newsig.HashAlgorithm),
                                      Gpgme.GetPubkeyAlgoName(newsig.PubkeyAlgorithm),
                                      newsig.Timestamp,
                                      newsig.Type);
                }
            }

            origin.Close();

            detachsig.Close();

            /////// VERIFY DATA (detached signature) ///////
            Console.Write("Verify a detached signature from file: original.txt.sig.. ");

            origin = new GpgmeFileData("original.txt",
                                       FileMode.Open,
                                       FileAccess.Read);

            detachsig = new GpgmeFileData("original.txt.sig",
                                          FileMode.Open,
                                          FileAccess.Read);

            VerificationResult verrst = ctx.Verify(
                detachsig,  // detached signature
                origin,     // original data
                null);      // should be NULL if a detached signature has been provided

            Console.WriteLine("done.");
            Console.WriteLine("Filename: {0}", verrst.FileName);

            // print out signature information
            if (verrst.Signature != null)
            {
                foreach (Signature sig in verrst.Signature)
                {
                    Console.WriteLine("Verification result (signature): "
                                      + "\n\tFingerprint: {0}"
                                      + "\n\tHash algorithm: {1}"
                                      + "\n\tKey algorithm: {2}"
                                      + "\n\tTimestamp: {3}"
                                      + "\n\tSummary: {4}"
                                      + "\n\tValidity: {5}",
                                      sig.Fingerprint,
                                      Gpgme.GetHashAlgoName(sig.HashAlgorithm),
                                      Gpgme.GetPubkeyAlgoName(sig.PubkeyAlgorithm),
                                      sig.Timestamp,
                                      sig.Summary,
                                      sig.Validity);
                }
            }
        }
        public Key[] GetKeyList(string[] pattern, bool secretOnly)
        {
            if (ctx == null ||
                !(ctx.IsValid))
            {
                throw new InvalidContextException();
            }

            List <Key> list = new List <Key>();

            int reserved    = 0;
            int secret_only = 0;

            if (secretOnly)
            {
                secret_only = 1;
            }

            IntPtr[] parray = null;
            if (pattern != null)
            {
                parray = Gpgme.StringToCoTaskMemUTF8(pattern);
            }

            lock (ctx.CtxLock)
            {
                // no deadlock because the query is made by the same thread
                Protocol proto = ctx.Protocol;

                int err = 0;

                if (parray != null)
                {
                    err = libgpgme.gpgme_op_keylist_ext_start(
                        ctx.CtxPtr,
                        parray,
                        secret_only,
                        reserved);
                }
                else
                {
                    err = libgpgme.gpgme_op_keylist_start(
                        ctx.CtxPtr,
                        IntPtr.Zero,
                        secret_only);
                }

                while (err == 0)
                {
                    IntPtr keyPtr = (IntPtr)0;
                    err = libgpgme.gpgme_op_keylist_next(ctx.CtxPtr, out keyPtr);
                    if (err != 0)
                    {
                        break;
                    }

                    Key key = null;

                    if (proto == Protocol.OpenPGP)
                    {
                        key = new PgpKey(keyPtr);
                    }
                    else if (proto == Protocol.CMS)
                    {
                        key = new X509Key(keyPtr);
                    }
                    else
                    {
                        key = new Key(keyPtr);
                    }

                    list.Add(key);

                    //libgpgme.gpgme_key_release(keyPtr);
                }

                // Free memory
                if (parray != null)
                {
                    Gpgme.FreeStringArray(parray);
                }

                gpg_err_code_t errcode = libgpgme.gpgme_err_code(err);
                if (errcode != gpg_err_code_t.GPG_ERR_EOF)
                {
                    libgpgme.gpgme_op_keylist_end(ctx.CtxPtr);
                    throw new GpgmeException(Gpgme.GetStrError(err), err);
                }
            }
            return(list.ToArray());
        }
Esempio n. 22
0
        static void Main()
        {
            Context ctx = new Context();

            if (ctx.Protocol != Protocol.OpenPGP)
            {
                ctx.SetEngineInfo(Protocol.OpenPGP, null, null);
            }

            Console.WriteLine("Search Bob's PGP key in the default keyring..");

            const string SEARCHSTR = "*****@*****.**";
            IKeyStore    keyring   = ctx.KeyStore;

            // retrieve all keys that have Bob's email address
            Key[] keys = keyring.GetKeyList(SEARCHSTR, false);
            if (keys == null || keys.Length == 0)
            {
                Console.WriteLine("Cannot find Bob's PGP key {0} in your keyring.", SEARCHSTR);
                Console.WriteLine("You may want to create the PGP key by using the appropriate\n"
                                  + "sample in the Samples/ directory.");
                return;
            }

            // print a list of all returned keys
            foreach (Key key in keys)
            {
                if (key.Uid != null && key.Fingerprint != null)
                {
                    Console.WriteLine("Found key {0} with fingerprint {1}", key.Uid.Name, key.Fingerprint);
                }
            }

            // we are going to use the first key in the list
            PgpKey bob = (PgpKey)keys.First();

            if (bob.Uid == null || bob.Fingerprint == null)
            {
                throw new InvalidKeyException();
            }
            Console.WriteLine("\nUsing key {0}", bob.Fingerprint);

            // Change Bob's passphrase. This will usually pop-up a pin-entry window!
            ChangePassphrase(ctx, bob);

            // Add another PGP sub key to Bob's key.
            AddSubKey(ctx, bob);

            // Reload Bobs key (otherwise the new sub key is NOT visible)
            bob = (PgpKey)keyring.GetKey(bob.Fingerprint, false);

            // Display all sub keys
            DisplaySubKeys(bob);

            // Switch owner trust to "Never" an then back to "Ultimate"
            SwitchOwnerTrust(ctx, bob);

            // Disable & Enable Bob's key for usage.
            ToggleEnableDisableState(ctx, bob);

            // Set an expiration date for Bob's key (today + 5 years)
            SetExpirationDate(ctx, bob);
        }