Ejemplo n.º 1
0
        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;
        }
Ejemplo n.º 2
0
        public void AddSubkey(Context ctx, PgpSubkeyOptions options)
        {
            if (ctx == null)
                throw new ArgumentNullException("No context object supplied.");
            if (!ctx.IsValid)
                throw new InvalidContextException("An invalid context has been supplied.");

            if (options == null)
                throw new ArgumentNullException("No PgpSubkeyOptions object specified.");

            lock (settings.passLock)
            {
                lock (settings.subkeyLock)
                {
                    settings.subkeyOptions = options;
                    settings.subkeycapability = AlgorithmCapability.CanNothing;
                    settings.subkeyalgoquestion = 0;
                    options.cmdSend = false;

                    KeyEditOp op = KeyEditOp.AddSubkey;
                    GpgmeData data = new GpgmeMemoryData();

                    int err;
                    try
                    {
                        err = StartEdit(ctx, (IntPtr)op, data);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    gpg_err_code_t errcode = libgpgerror.gpg_err_code(err);
                    switch (errcode)
                    {
                        case gpg_err_code_t.GPG_ERR_NO_ERROR:
                            if (settings.subkeyalgoquestion > 1)
                                throw new NotSupportedException("GnuPG was not in expert mode. Customized subkeys are not supported.");
                            break;
                        case gpg_err_code_t.GPG_ERR_BAD_PASSPHRASE:
                            throw new BadPassphraseException(settings.passSettings.GetPassphraseInfo());
                        default:
                            throw new GpgmeException("An unknown error occurred. Error: "
                                + err.ToString(), err);
                    }
                }
            }
        }
Ejemplo n.º 3
0
        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;

            // 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.ToString();

            // 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(new PassphraseDelegate(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();
            plain = null;
            cipher.Close();
            cipher = null;

            /////// 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);
                }
            }

            return;
        }
Ejemplo n.º 4
0
        public void Sign(Context ctx, PgpSignatureOptions options)
        {
            if (ctx == null)
                throw new ArgumentNullException("No context object supplied.");
            if (!ctx.IsValid)
                throw new InvalidContextException("An invalid context has been supplied.");

            if (options == null)
                throw new ArgumentNullException("No PgpSignatureOptions object specified.");

            lock (settings.passLock)
            {
                lock (settings.sigLock)
                {
                    settings.sigOptions = options;

                    // reset object
                    options.cmdSend = false;
                    options.nUid = 0;
                    options.forceQuit = false;
                    options.signAllUids = true;

                    // specify key edit operation;
                    KeyEditOp op = KeyEditOp.Signature;

                    // output data
                    GpgmeData data = new GpgmeMemoryData();

                    int err;

                    try
                    {
                        err = StartEdit(ctx, (IntPtr)op, data);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    gpg_err_code_t errcode = libgpgerror.gpg_err_code(err);

                    switch (errcode)
                    {
                        case gpg_err_code_t.GPG_ERR_NO_ERROR:
                            break;
                        case gpg_err_code_t.GPG_ERR_BAD_PASSPHRASE:
                            throw new BadPassphraseException(settings.passSettings.GetPassphraseInfo());

                        default:
                            throw new GpgmeException("An unknown error occurred. Error: "
                                + err.ToString(), err);
                    }
                }
            }
        }
Ejemplo n.º 5
0
        public void SetOwnerTrust(Context ctx, PgpOwnerTrust trust)
        {
            if (ctx == null)
                throw new ArgumentNullException("No context object supplied.");
            if (!ctx.IsValid)
                throw new InvalidContextException("An invalid context has been supplied.");

            lock (settings.trustLock)
            {
                settings.trustOptions = new PgpTrustOptions();
                settings.trustOptions.trust = trust;

                // specify key edit operation;
                KeyEditOp op = KeyEditOp.Trust;

                // output data
                GpgmeData data = new GpgmeMemoryData();

                int err;

                try
                {
                    err = StartEdit(ctx, (IntPtr)op, data);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                gpg_err_code_t errcode = libgpgerror.gpg_err_code(err);

                switch (errcode)
                {
                    case gpg_err_code_t.GPG_ERR_NO_ERROR:
                        break;
                    case gpg_err_code_t.GPG_ERR_BAD_PASSPHRASE:
                        throw new BadPassphraseException(settings.passSettings.GetPassphraseInfo());

                    default:
                        throw new GpgmeException("An unknown error occurred.", err);
                }
            }
        }
Ejemplo n.º 6
0
        public void RevokeSignature(Context ctx, PgpRevokeSignatureOptions options)
        {
            if (ctx == null)
                throw new ArgumentNullException("No context object supplied.");
            if (!ctx.IsValid)
                throw new InvalidContextException("An invalid context has been supplied.");

            if (options == null)
                throw new ArgumentNullException("No revocation options specified.");

            if (options.SelectedSignatures == null ||
                options.SelectedSignatures.Length == 0)
                throw new ArgumentException("No signatures selected.");

            lock (settings.passLock)
            {
                lock (settings.revsigLock)
                {
                    settings.revsigOptions = options;

                    // reset object
                    options.cmdSend     = false;
                    options.uidSend     = false;
                    options.reasonSend  = false;
                    // reset reason text counter (gnupg prompts for each line)
                    options.nreasonTxt  = 0;
                    /* reset own signature counter (user could have signed the key with more
                     * than one of his keys. */
                    options.nrevokenum  = 0;

                    // specify key edit operation;
                    KeyEditOp op = KeyEditOp.RevokeSignature;

                    // output data
                    GpgmeData data = new GpgmeMemoryData();

                    int err;

                    try
                    {
                        err = StartEdit(ctx, (IntPtr)op, data);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    gpg_err_code_t errcode = libgpgerror.gpg_err_code(err);

                    switch (errcode)
                    {
                        case gpg_err_code_t.GPG_ERR_NO_ERROR:
                            break;
                        case gpg_err_code_t.GPG_ERR_BAD_PASSPHRASE:
                            throw new BadPassphraseException(settings.passSettings.GetPassphraseInfo());

                        default:
                            throw new GpgmeException("An unknown error occurred. Error: "
                                + err.ToString(), err);
                    }
                }
            }
        }
Ejemplo n.º 7
0
        public void DeleteSignature(Context ctx, PgpDeleteSignatureOptions options)
        {
            if (ctx == null || !ctx.IsValid)
                throw new InvalidContextException();

            if (options == null)
                throw new ArgumentNullException("No PgpDeleteSignatureOptions object specified.");

            if (options.SelectedSignatures == null ||
                options.SelectedSignatures.Length == 0)
                throw new ArgumentException("No signatures selected.");

            lock (settings.passLock)
            {
                lock (settings.delsigLock)
                {
                    settings.delsigOptions = options;

                    // reset object
                    options.cmdSend = false;
                    options.uidSend = false;
                    options.ndeletenum = 0;

                    // specify key edit operation;
                    KeyEditOp op = KeyEditOp.DeleteSignature;

                    // output data
                    GpgmeData data = new GpgmeMemoryData();

                    int err;

                    try
                    {
                        err = StartEdit(ctx, (IntPtr)op, data);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    gpg_err_code_t errcode = libgpgerror.gpg_err_code(err);

                    switch (errcode)
                    {
                        case gpg_err_code_t.GPG_ERR_NO_ERROR:
                            break;
                        case gpg_err_code_t.GPG_ERR_BAD_PASSPHRASE:
                            throw new BadPassphraseException(settings.passSettings.GetPassphraseInfo());

                        default:
                            throw new GpgmeException("An unknown error occurred. Error: "
                                + err.ToString(), err);
                    }
                }
            }
        }
Ejemplo n.º 8
0
        public void ChangePassphrase(Context ctx, PgpPassphraseOptions options)
        {
            if (ctx == null)
                throw new ArgumentNullException("No context object supplied.");
            if (!ctx.IsValid)
                throw new InvalidContextException("An invalid context has been supplied.");

            if (ctx.HasPassphraseFunction)
                throw new InvalidContextException("The context must not have a passphrase callback function.");

            if (options == null)
                throw new ArgumentNullException("PgpPassphraseOptions object required.");

            lock (settings.passLock)
            {
                lock (settings.newpassLock)
                {
                    // specify key edit operation;
                    KeyEditOp op = KeyEditOp.Passphrase;
                    settings.passOptions = options;

                    // reset object
                    options.passphraseSendCmd = false;
                    options.needoldpw = true;
                    options.missingpasswd = false;
                    options.aborthandler = false;
                    options.emptypasswdcount = 0;

                    // output data
                    GpgmeData data = new GpgmeMemoryData();

                    int err;
                    try
                    {
                        err = StartEdit(ctx, (IntPtr)op, data);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    gpg_err_code_t errcode = libgpgerror.gpg_err_code(err);

                    switch (errcode)
                    {
                        case gpg_err_code_t.GPG_ERR_NO_ERROR:
                            break;
                        case gpg_err_code_t.GPG_ERR_BAD_PASSPHRASE:
                            // This could be thrown if the user has chosen an empty password.
                            if (options.missingpasswd == true
                                && options.EmptyOkay == false
                                && options.aborthandler == false
                                && (options.emptypasswdcount < PgpPassphraseOptions.MAX_PASSWD_COUNT))
                            {
                                break;
                            }
                            else
                                throw new BadPassphraseException(settings.passSettings.GetPassphraseInfo());
                        default:
                            if (options.missingpasswd && options.aborthandler)
                                throw new EmptyPassphraseException(settings.passSettings.GetPassphraseInfo());
                            else
                                throw new GpgmeException("An unknown error occurred. Error:"
                                    + err.ToString(), err);
                    }
                }
            }
        }