예제 #1
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);
                }
            }
        }
예제 #2
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);
                }
            }
        }