/// <summary>
        /// Implementation of your slot.
        /// </summary>
        /// <param name="signaler">Signaler that raised the signal.</param>
        /// <param name="input">Arguments to your slot.</param>
        public void Signal(ISignaler signaler, Node input)
        {
            // Sanity checking invocation.
            var keyPlainText = input.GetEx <string>() ??
                               throw new ArgumentException("No value provided to [pgp.keys.private.import]");
            var lambda = input.Children.FirstOrDefault(x => x.Name == ".lambda") ??
                         throw new ArgumentException("No [.lambda] provided to [pgp.keys.private.import]");

            // Unwrapping key(s) and iterating through them, importing them one at the time.
            using (var memStream = new MemoryStream(Encoding.UTF8.GetBytes(keyPlainText)))
            {
                using (var armored = new ArmoredInputStream(memStream))
                {
                    var key = new PgpSecretKeyRing(armored);
                    foreach (PgpSecretKey idxKey in key.GetSecretKeys())
                    {
                        InvokeLambda(signaler, lambda, idxKey);
                    }

                    // Then doing public key for master key in secret key chain.
                    var publicKey = key.GetPublicKey();
                    if (publicKey != null)
                    {
                        PgpKeysPublicImport.InvokeLambda(signaler, lambda, publicKey);
                    }
                }
            }
        }
        private void repeatHeaderTest()
        {
            MemoryStream        bOut = new MemoryStream();
            ArmoredOutputStream aOut = new ArmoredOutputStream(bOut);

            aOut.SetHeader("Comment", "Line 1");
            aOut.AddHeader("Comment", "Line 2");

            aOut.Write(sample, 0, sample.Length);

            aOut.Close();

            MemoryStream       bIn = new MemoryStream(bOut.ToArray(), false);
            ArmoredInputStream aIn = new ArmoredInputStream(bIn, true);

            string[] hdrs  = aIn.GetArmorHeaders();
            int      count = 0;

            for (int i = 0; i != hdrs.Length; i++)
            {
                if (hdrs[i].IndexOf("Comment: ") == 0)
                {
                    count++;
                }
            }

            IsEquals(2, count);
        }
Example #3
0
        /// <summary>
        /// Verify signature
        /// </summary>
        /// <param name="data">Data to verify</param>
        /// <returns>Return true if signature validates, else false.</returns>
        public bool Verify(byte[] data)
        {
            Context = new CryptoContext(Context);

            using (var dataIn = new MemoryStream(data))
                using (var armoredIn = new ArmoredInputStream(dataIn))
                {
                    if (!armoredIn.IsClearText())
                    {
                        var factory = new PgpObjectFactory(armoredIn);

                        DecryptHandlePgpObject(factory.NextPgpObject());
                        if (Context.FailedIntegrityCheck)
                        {
                            throw new VerifyException("Error, failed validation check.");
                        }

                        if (!Context.IsSigned)
                        {
                            throw new CryptoException("Error, message is not signed.");
                        }

                        return(Context.SignatureValidated);
                    }
                }

            return(VerifyClear(data));
        }
Example #4
0
        /// <summary>
        /// Imports public pgp keys from the specified stream.
        /// </summary>
        /// <remarks>
        /// Imports public pgp keys from the specified stream.
        /// </remarks>
        /// <param name="stream">The raw key data.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="stream"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// <para>An error occurred while parsing the raw key-ring data</para>
        /// <para>-or-</para>
        /// <para>An error occured while saving the public key-ring bundle.</para>
        /// </exception>
        public override void Import(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            using (var armored = new ArmoredInputStream(stream))
                Import(new PgpPublicKeyRingBundle(armored));
        }
 /// <summary>
 /// Returns a PGP secret key ring from the given ASCII armored secret key string content.
 /// </summary>
 /// <param name="key"></param>
 /// <returns></returns>
 public static PgpSecretKeyRing GetSecretKeyRingFromAsciiArmored(string key)
 {
     using (var memStream = new MemoryStream(Encoding.UTF8.GetBytes(key)))
     {
         using (var armored = new ArmoredInputStream(memStream))
         {
             return(new PgpSecretKeyRing(armored));
         }
     }
 }
Example #6
0
        /// <summary>
        /// Decrypt and verify signature of data.
        /// </summary>
        /// <param name="data">Data to decrypt and verify</param>
        /// <returns>Returns decrypted data if signature verifies.</returns>
        public byte[] DecryptAndVerify(byte[] data, bool ignoreIntegrityCheck = false)
        {
            Context = new CryptoContext(Context);

            var isArmored = ASCIIEncoding.ASCII.GetString(data).IndexOf("-----BEGIN PGP MESSAGE-----") > -1;

            using (var dataIn = new MemoryStream(data))
            {
                if (isArmored)
                {
                    using (var armoredIn = new ArmoredInputStream(dataIn))
                    {
                        var factory = new PgpObjectFactory(armoredIn);

                        while (true)
                        {
                            var obj = factory.NextPgpObject();
                            if (obj is PgpMarker)
                            {
                                continue;
                            }

                            var ret = DecryptHandlePgpObject(obj);
                            if (Context.FailedIntegrityCheck && !ignoreIntegrityCheck)
                            {
                                throw new VerifyException("Data not integrity protected.");
                            }

                            return(ret);
                        }
                    }
                }
                else
                {
                    var factory = new PgpObjectFactory(dataIn);

                    while (true)
                    {
                        var obj = factory.NextPgpObject();
                        if (obj is PgpMarker)
                        {
                            continue;
                        }

                        var ret = DecryptHandlePgpObject(obj);
                        if (Context.FailedIntegrityCheck && !ignoreIntegrityCheck)
                        {
                            throw new VerifyException("Data not integrity protected.");
                        }

                        return(ret);
                    }
                }
            }
        }
 /// <summary>
 /// Returns public key from armored ASCII key content.
 /// </summary>
 /// <param name="key">Armored text format containing key.</param>
 /// <returns></returns>
 public static PgpPublicKey GetPublicKeyFromAsciiArmored(string key)
 {
     using (var memStream = new MemoryStream(Encoding.UTF8.GetBytes(key)))
     {
         using (var armored = new ArmoredInputStream(memStream))
         {
             var result = new PgpPublicKeyRing(armored);
             return(result.GetPublicKey());
         }
     }
 }
Example #8
0
        /// <summary>
        /// Decrypt and verify signature of data.
        /// </summary>
        /// <param name="data">Data to decrypt and verify</param>
        /// <returns>Returns decrypted data if signature verifies.</returns>
        public byte[] DecryptAndVerify(byte[] data, bool ignoreIntegrityCheck = false)
        {
            Context = new CryptoContext(Context);

            var isArmored = ASCIIEncoding.ASCII.GetString(data).Contains("-----BEGIN PGP MESSAGE-----");

            using (var dataIn = new MemoryStream(data))
            {
                if (!isArmored)
                {
                    return(DecryptBytes(ignoreIntegrityCheck, dataIn));
                }

                using (var armoredIn = new ArmoredInputStream(dataIn))
                {
                    return(DecryptBytes(ignoreIntegrityCheck, armoredIn));
                }
            }
        }
        private static void p5_crypto_preview_public_pgp_key(ApplicationContext context, ActiveEventArgs e)
        {
            // House cleaning
            using (new ArgsRemover(e.Args, true)) {
                // Looping through each public key (in ascii armored format) and importing into GnuPG database
                foreach (var idxKey in XUtil.Iterate <string> (context, e.Args))
                {
                    // Creating armored input stream to wrap key
                    using (var memStream = new MemoryStream(Encoding.UTF8.GetBytes(idxKey.Replace("\r\n", "\n")))) {
                        using (var armored = new ArmoredInputStream(memStream)) {
                            var keys = new PgpPublicKeyRing(armored);

                            // Now returning key details to caller.
                            foreach (PgpPublicKey key in keys.GetPublicKeys())
                            {
                                var node = e.Args.Add(BitConverter.ToString(key.GetFingerprint()).Replace("-", "")).LastChild;
                                node.Add("id", ((int)key.KeyId).ToString("X"));
                                node.Add("algorithm", key.Algorithm.ToString());
                                node.Add("strength", key.BitStrength);
                                node.Add("creation-time", key.CreationTime);
                                node.Add("is-encryption-key", key.IsEncryptionKey);
                                node.Add("is-master-key", key.IsMasterKey);
                                node.Add("is-revoked", key.IsRevoked());
                                node.Add("version", key.Version);
                                DateTime expires = key.CreationTime.AddSeconds(key.GetValidSeconds());
                                node.Add("expires", expires);
                                foreach (var idxUserId in key.GetUserIds())
                                {
                                    if (idxUserId is string)
                                    {
                                        node.FindOrInsert("user-ids").Add("", idxUserId);
                                    }
                                }
                                foreach (PgpSignature signature in key.GetSignatures())
                                {
                                    node.FindOrInsert("signed-by").Add(((int)signature.KeyId).ToString("X"), signature.CreationTime);
                                }
                            }
                        }
                    }
                }
            }
        }
Example #10
0
 private static void p5_crypto_import_public_pgp_key(ApplicationContext context, ActiveEventArgs e)
 {
     // House cleaning
     using (new ArgsRemover(e.Args, true)) {
         // Creating new GnuPG context
         using (var ctx = new GnuPrivacyContext()) {
             // Looping through each public key (in ascii armored format) and importing into GnuPG database
             foreach (var idxKey in XUtil.Iterate <string> (context, e.Args))
             {
                 // Creating armored input stream to wrap key
                 using (var memStream = new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(idxKey))) {
                     using (var armored = new ArmoredInputStream(memStream)) {
                         var key = new PgpPublicKeyRing(armored);
                         ctx.Import(key);
                     }
                 }
             }
         }
     }
 }
        private void blankLineTest()
        {
            byte[]             blankLineBytes = Encoding.ASCII.GetBytes(blankLineData);
            MemoryStream       bIn            = new MemoryStream(blankLineBytes, false);
            ArmoredInputStream aIn            = new ArmoredInputStream(bIn, true);

            MemoryStream bOut = new MemoryStream();
            int          c;

            while ((c = aIn.ReadByte()) >= 0)
            {
                bOut.WriteByte((byte)c);
            }

            byte[] expected = Encoding.ASCII.GetBytes("Hello World!");

            if (!Arrays.AreEqual(expected, bOut.ToArray()))
            {
                Fail("Incorrect message retrieved in blank line test.");
            }
        }
 private static void p5_crypto_import_private_pgp_key(ApplicationContext context, ActiveEventArgs e)
 {
     // House cleaning
     using (new ArgsRemover(e.Args, true)) {
         // Creating new GnuPG context
         using (var ctx = new GnuPrivacyContext(true)) {
             // Looping through each public key (in ascii armored format) and importing into GnuPG database
             foreach (var idxKey in XUtil.Iterate <string> (context, e.Args))
             {
                 // Creating armored input stream to wrap key
                 using (var memStream = new MemoryStream(Encoding.UTF8.GetBytes(idxKey.Replace("\r\n", "\n")))) {
                     using (var armored = new ArmoredInputStream(memStream)) {
                         var key = new PgpSecretKeyRing(armored);
                         ctx.Import(key);
                         e.Args.Add(BitConverter.ToString(key.GetPublicKey().GetFingerprint()).Replace("-", ""));
                     }
                 }
             }
         }
     }
 }
        static void p5_crypto_pgp_keys_private_import(ApplicationContext context, ActiveEventArgs e)
        {
            // House cleaning.
            using (new ArgsRemover(e.Args, true)) {
                // Creating new PGP context.
                using (var ctx = context.RaiseEvent(".p5.crypto.pgp-keys.context.create", new Node("", true)).Get <OpenPgpContext> (context)) {
                    // Looping through each private key (in ascii armored format) and importing into context.
                    foreach (var idxKey in XUtil.Iterate <string> (context, e.Args))
                    {
                        // Creating armored input stream to wrap key.
                        using (var memStream = new MemoryStream(Encoding.UTF8.GetBytes(idxKey.Replace("\r\n", "\n")))) {
                            using (var armored = new ArmoredInputStream(memStream)) {
                                var key = new PgpSecretKeyRing(armored);
                                ctx.Import(key);

                                // Returning fingerprint of key that was successfully imported to caller.
                                e.Args.Add(Fingerprint.FingerprintString(key.GetPublicKey().GetFingerprint()));
                            }
                        }
                    }
                }
            }
        }
Example #14
0
        public static string DecryptKey(string encryptedAESKey, string privateKeyFilename, string passPhrase)
        {
            var inputStream   = new MemoryStream(Encoding.ASCII.GetBytes(encryptedAESKey));
            var armoredStream = new ArmoredInputStream(inputStream);

            //var decoderStream = PgpUtilities.GetDecoderStream(inputStream);

            try
            {
                PgpObjectFactory     pgpF = new PgpObjectFactory(armoredStream);
                PgpEncryptedDataList enc;

                PgpObject o = pgpF.NextPgpObject();
                //
                // the first object might be a PGP marker packet.
                //
                if (o is PgpEncryptedDataList)
                {
                    enc = (PgpEncryptedDataList)o;
                }
                else
                {
                    enc = (PgpEncryptedDataList)pgpF.NextPgpObject();
                }

                //
                // find the secret key
                //
                PgpPrivateKey sKey = ReadPrivateKey(privateKeyFilename, passPhrase);

                if (sKey == null)
                {
                    throw new ArgumentException("secret key for message not found.");
                }

                PgpPublicKeyEncryptedData pbe = null;
                foreach (var pked in enc.GetEncryptedDataObjects().Cast <PgpPublicKeyEncryptedData>())
                {
                    if (pked.KeyId == sKey.KeyId)
                    {
                        pbe = pked;
                        break;
                    }
                }
                if (pbe == null)
                {
                    Console.WriteLine("Invalid Key");
                    return("");
                }
                var cleartextStream = pbe.GetDataStream(sKey);

                var plainObjectFactory = new PgpObjectFactory(cleartextStream);

                var message = plainObjectFactory.NextPgpObject();
                var result  = "";
                if (message is PgpLiteralData)
                {
                    PgpLiteralData ld = (PgpLiteralData)message;

                    var output    = new MemoryStream();
                    var decrypted = ld.GetInputStream();
                    decrypted.CopyTo(output);
                    result = Encoding.ASCII.GetString(output.ToArray());
                }
                else
                {
                    throw new PgpException("message is not a simple encrypted file - type unknown.");
                }

                if (pbe.IsIntegrityProtected())
                {
                    if (!pbe.Verify())
                    {
                        Console.Error.WriteLine("message failed integrity check");
                    }
                    else
                    {
                        Console.Error.WriteLine("message integrity check passed");
                    }
                }
                return(result);
            }
            catch (PgpException e)
            {
                Console.Error.WriteLine(e);

                Exception underlyingException = e.InnerException;
                if (underlyingException != null)
                {
                    Console.Error.WriteLine(underlyingException.Message);
                    Console.Error.WriteLine(underlyingException.StackTrace);
                }
            }
            return("");
        }
        /*
         * verify a clear text signed file
         */
        public static PgpSignatureInfo VerifyFile(
            Stream inputStream,
            Stream pubkeyRing)
        {
            var aIn = new ArmoredInputStream(inputStream);

            Stream outStr = new MemoryStream();
            //
            // write out signed section using the local line separator.
            // note: trailing white space needs to be removed from the end of
            // each line RFC 4880 Section 7.1
            //
            var lineOut   = new MemoryStream();
            var lookAhead = ReadInputLine(lineOut, aIn);
            var newline   = Encoding.ASCII.GetBytes(Environment.NewLine);

            if (lookAhead != -1 && aIn.IsClearText())
            {
                var line = lineOut.ToArray();
                outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line));
                outStr.Write(newline, 0, newline.Length);

                while (lookAhead != -1 && aIn.IsClearText())
                {
                    lookAhead = ReadInputLine(lineOut, lookAhead, aIn);

                    line = lineOut.ToArray();
                    outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line));
                    outStr.Write(newline, 0, newline.Length);
                }
            }

            //outStr.Close();

            var pgpRings = new PgpPublicKeyRingBundle(pubkeyRing);

            var pgpFact = new PgpObjectFactory(aIn);
            var p3      = (PgpSignatureList)pgpFact.NextPgpObject();
            var sig     = p3[0];

            sig.InitVerify(pgpRings.GetPublicKey(sig.KeyId));

            //
            // read the input, making sure we ignore the last newline.
            //
            var sigIn = outStr;

            // Set position of stream to start.
            sigIn.Position = 0;
            lookAhead      = ReadInputLine(lineOut, sigIn);

            ProcessLine(sig, lineOut.ToArray());

            if (lookAhead != -1)
            {
                do
                {
                    lookAhead = ReadInputLine(lineOut, lookAhead, sigIn);

                    sig.Update((byte)'\r');
                    sig.Update((byte)'\n');

                    ProcessLine(sig, lineOut.ToArray());
                }while (lookAhead != -1);
            }

            var siginfo = new PgpSignatureInfo();

            if (sig.Verify())
            {
                siginfo.KeyId         = String.Format("{0:X}", sig.KeyId);
                siginfo.Valid         = true;
                siginfo.Version       = sig.Version;
                siginfo.Created       = sig.CreationTime;
                siginfo.HashAlgorithm = sig.HashAlgorithm;
                siginfo.Signature     = sig;
                return(siginfo);
            }
            siginfo.KeyId         = String.Format("{0:X}", sig.KeyId);
            siginfo.Valid         = false;
            siginfo.Version       = sig.Version;
            siginfo.Created       = sig.CreationTime;
            siginfo.HashAlgorithm = sig.HashAlgorithm;
            siginfo.Signature     = sig;

            return(siginfo);
        }
Example #16
0
        /// <summary>
        /// Verifies clear text PGP signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpVerifyClearTextSignature Returns: Object {string FilePath, Boolean Verified}
        /// </summary>
        public static Result PGPVerifyClearTextSignFile(Input input)
        {
            Stream             inStr  = File.OpenRead(input.InputFile);
            ArmoredInputStream aIn    = new ArmoredInputStream(inStr);
            Stream             outStr = File.Create(input.OutputFile);

            //
            // write out signed section using the local line separator.
            // note: trailing white space needs to be removed from the end of
            // each line RFC 4880 Section 7.1
            //
            MemoryStream lineOut   = new MemoryStream();
            int          lookAhead = ReadInputLine(lineOut, aIn);

            byte[] lineSep = Encoding.ASCII.GetBytes(Environment.NewLine);;


            if (lookAhead != -1 && aIn.IsClearText())
            {
                byte[] line = lineOut.ToArray();
                outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line));
                outStr.Write(lineSep, 0, lineSep.Length);

                while (lookAhead != -1 && aIn.IsClearText())
                {
                    lookAhead = ReadInputLine(lineOut, lookAhead, aIn);

                    line = lineOut.ToArray();
                    outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line));
                    outStr.Write(lineSep, 0, lineSep.Length);
                }
            }
            else
            {
                // a single line file
                if (lookAhead != -1)
                {
                    byte[] line = lineOut.ToArray();
                    outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line));
                    outStr.Write(lineSep, 0, lineSep.Length);
                }
            }
            outStr.Close();

            PgpPublicKeyRingBundle pgpRings = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(File.OpenRead(input.PublicKeyFile)));

            PgpObjectFactory pgpFact = new PgpObjectFactory(aIn);
            PgpSignatureList p3      = (PgpSignatureList)pgpFact.NextPgpObject();
            PgpSignature     sig     = p3[0];

            inStr.Close();

            sig.InitVerify(pgpRings.GetPublicKey(sig.KeyId));
            // read the input, making sure we ignore the last newline.
            Stream sigIn = File.OpenRead(input.OutputFile);

            lookAhead = ReadInputLine(lineOut, sigIn);
            ProcessLine(sig, lineOut.ToArray());
            if (lookAhead != -1)
            {
                do
                {
                    lookAhead = ReadInputLine(lineOut, lookAhead, sigIn);

                    sig.Update((byte)'\r');
                    sig.Update((byte)'\n');

                    ProcessLine(sig, lineOut.ToArray());
                }while (lookAhead != -1);
            }

            bool verified = sig.Verify();

            sigIn.Close();
            Result ret = new Result
            {
                FilePath = input.OutputFile,
                Verified = verified
            };

            return(ret);
        }
        private void messageTest(
            string message,
            string type)
        {
            ArmoredInputStream aIn = new ArmoredInputStream(
                new MemoryStream(Encoding.ASCII.GetBytes(message)));

            string[] headers = aIn.GetArmorHeaders();

            if (headers == null || headers.Length != 1)
            {
                Fail("wrong number of headers found");
            }

            if (!"Hash: SHA256".Equals(headers[0]))
            {
                Fail("header value wrong: " + headers[0]);
            }

            //
            // read the input, making sure we ingore the last newline.
            //
            MemoryStream bOut = new MemoryStream();
            int          ch;

            while ((ch = aIn.ReadByte()) >= 0 && aIn.IsClearText())
            {
                bOut.WriteByte((byte)ch);
            }

            PgpPublicKeyRingBundle pgpRings = new PgpPublicKeyRingBundle(publicKey);

            PgpObjectFactory pgpFact = new PgpObjectFactory(aIn);
            PgpSignatureList p3      = (PgpSignatureList)pgpFact.NextPgpObject();
            PgpSignature     sig     = p3[0];

            sig.InitVerify(pgpRings.GetPublicKey(sig.KeyId));

            MemoryStream lineOut   = new MemoryStream();
            Stream       sigIn     = new MemoryStream(bOut.ToArray(), false);
            int          lookAhead = ReadInputLine(lineOut, sigIn);

            ProcessLine(sig, lineOut.ToArray());

            if (lookAhead != -1)
            {
                do
                {
                    lookAhead = ReadInputLine(lineOut, lookAhead, sigIn);

                    sig.Update((byte)'\r');
                    sig.Update((byte)'\n');

                    ProcessLine(sig, lineOut.ToArray());
                }while (lookAhead != -1);
            }

            if (!sig.Verify())
            {
                Fail("signature failed to verify m_in " + type);
            }
        }
Example #18
0
        public static bool VerifySig(byte[] asc, string sig, out string message)
        {
            try
            {
                foreach (PgpPublicKey pubkey in new PgpPublicKeyRing(GetStream(asc)).GetPublicKeys().OfType <PgpPublicKey>()) //java madness
                {
                    //AGAIN MADNESS THIS MAKE PERFECT SENSE !
                    ArmoredInputStream sigInput = new ArmoredInputStream(new MemoryStream(Encoding.UTF8.GetBytes(sig)));

                    //
                    // read the input, making sure we ingore the last newline.
                    //
                    int          ch;
                    string       newLine = null;
                    MemoryStream bOut    = new MemoryStream();

                    while ((ch = sigInput.ReadByte()) >= 0 && sigInput.IsClearText())
                    {
                        if (newLine != null)
                        {
                            foreach (var c in newLine)
                            {
                                bOut.WriteByte((byte)c);
                            }
                            newLine = null;
                        }
                        if (ch == '\r')
                        {
                            ch = sigInput.ReadByte();
                            if (ch == '\n')
                            {
                                newLine = "\r\n";
                                continue;
                            }
                        }
                        if (ch == '\n')
                        {
                            newLine = "\n";
                            continue;
                        }

                        bOut.WriteByte((byte)ch);
                    }

                    var toSign = bOut.ToArray();
                    message = Encoding.UTF8.GetString(toSign);

                    PgpObjectFactory pgpObjFactory = new PgpObjectFactory(sigInput);
                    var          list   = (PgpSignatureList)pgpObjFactory.NextPgpObject();
                    PgpSignature pgpSig = list[0];
                    pgpSig.InitVerify(pubkey);
                    pgpSig.Update(toSign);
                    var result = pgpSig.Verify();
                    if (result)
                    {
                        return(result);
                    }
                    Regex endofline = new Regex("[ ]+?(\r?)\n");
                    message = endofline.Replace(message, "$1\n");
                    toSign  = Encoding.UTF8.GetBytes(message);
                    pgpSig.InitVerify(pubkey);
                    pgpSig.Update(toSign);
                    result = pgpSig.Verify();
                    if (result)
                    {
                        return(result);
                    }
                }
            }
            catch //Don't do it at home kids
            {
            }
            message = null;
            return(false);
        }
		private void messageTest(
			string message,
			string type)
		{
			ArmoredInputStream aIn = new ArmoredInputStream(
				new MemoryStream(Encoding.ASCII.GetBytes(message)));

			string[] headers = aIn.GetArmorHeaders();

			if (headers == null || headers.Length != 1)
			{
				Fail("wrong number of headers found");
			}

			if (!"Hash: SHA256".Equals(headers[0]))
			{
				Fail("header value wrong: " + headers[0]);
			}

			//
			// read the input, making sure we ingore the last newline.
			//
			MemoryStream bOut = new MemoryStream();
			int ch;

			while ((ch = aIn.ReadByte()) >= 0 && aIn.IsClearText())
			{
				bOut.WriteByte((byte)ch);
			}

			PgpPublicKeyRingBundle pgpRings = new PgpPublicKeyRingBundle(publicKey);

			PgpObjectFactory	pgpFact = new PgpObjectFactory(aIn);
			PgpSignatureList	p3 = (PgpSignatureList)pgpFact.NextPgpObject();
			PgpSignature		sig = p3[0];

			sig.InitVerify(pgpRings.GetPublicKey(sig.KeyId));

			MemoryStream lineOut = new MemoryStream();
			Stream sigIn = new MemoryStream(bOut.ToArray(), false);
			int lookAhead = ReadInputLine(lineOut, sigIn);

			ProcessLine(sig, lineOut.ToArray());

			if (lookAhead != -1)
			{
				do
				{
					lookAhead = ReadInputLine(lineOut, lookAhead, sigIn);

					sig.Update((byte) '\r');
					sig.Update((byte) '\n');

					ProcessLine(sig, lineOut.ToArray());
				}
				while (lookAhead != -1);
			}

			if (!sig.Verify())
			{
				Fail("signature failed to verify m_in " + type);
			}
		}
        /*
         * verify a clear text signed file
         */
        private static void VerifyFile(
            Stream inputStream,
            Stream keyIn,
            string resultName)
        {
            ArmoredInputStream aIn    = new ArmoredInputStream(inputStream);
            Stream             outStr = File.Create(resultName);

            //
            // write out signed section using the local line separator.
            // note: trailing white space needs to be removed from the end of
            // each line RFC 4880 Section 7.1
            //
            MemoryStream lineOut   = new MemoryStream();
            int          lookAhead = ReadInputLine(lineOut, aIn);

            byte[] lineSep = LineSeparator;

            if (lookAhead != -1 && aIn.IsClearText())
            {
                byte[] line = lineOut.ToArray();
                outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line));
                outStr.Write(lineSep, 0, lineSep.Length);

                while (lookAhead != -1 && aIn.IsClearText())
                {
                    lookAhead = ReadInputLine(lineOut, lookAhead, aIn);

                    line = lineOut.ToArray();
                    outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line));
                    outStr.Write(lineSep, 0, lineSep.Length);
                }
            }
            else
            {
                // a single line file
                if (lookAhead != -1)
                {
                    byte[] line = lineOut.ToArray();
                    outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line));
                    outStr.Write(lineSep, 0, lineSep.Length);
                }
            }

            outStr.Close();

            PgpPublicKeyRingBundle pgpRings = new PgpPublicKeyRingBundle(keyIn);

            PgpObjectFactory pgpFact = new PgpObjectFactory(aIn);
            PgpSignatureList p3      = (PgpSignatureList)pgpFact.NextPgpObject();
            PgpSignature     sig     = p3[0];

            sig.InitVerify(pgpRings.GetPublicKey(sig.KeyId));

            //
            // read the input, making sure we ignore the last newline.
            //
            Stream sigIn = File.OpenRead(resultName);

            lookAhead = ReadInputLine(lineOut, sigIn);

            ProcessLine(sig, lineOut.ToArray());

            if (lookAhead != -1)
            {
                do
                {
                    lookAhead = ReadInputLine(lineOut, lookAhead, sigIn);

                    sig.Update((byte)'\r');
                    sig.Update((byte)'\n');

                    ProcessLine(sig, lineOut.ToArray());
                }while (lookAhead != -1);
            }

            sigIn.Close();

            if (sig.Verify())
            {
                Console.WriteLine("signature verified.");
            }
            else
            {
                Console.WriteLine("signature verification failed.");
            }
        }
Example #21
0
        public static bool ReadAndVerifyFile(Stream inputStream, Stream keyIn, out Stream cleartextOut)
        {
            // Count any exception as BouncyCastle failing to parse something, because of corruption maybe?
            try
            {
                // Disposing this will close the underlying stream, which we don't want to do
                var armouredInputStream = new ArmoredInputStream(inputStream);

                // This stream is returned, so is not disposed
                var cleartextStream = new MemoryStream();

                int chr;

                while ((chr = armouredInputStream.ReadByte()) >= 0 && armouredInputStream.IsClearText())
                {
                    cleartextStream.WriteByte((byte)chr);
                }

                // Strip the trailing newline if set...
                cleartextStream.Position = Math.Max(0, cleartextStream.Position - 2);
                int count = 0;
                if (cleartextStream.ReadByte() == '\r')
                {
                    count++;
                }
                if (cleartextStream.ReadByte() == '\n')
                {
                    count++;
                }
                cleartextStream.SetLength(cleartextStream.Length - count);

                cleartextStream.Position = 0;

                // This will either return inputStream, or a new ArmouredStream(inputStream)
                // Either way, disposing it will close the underlying stream, which we don't want to do
                var decoderStream = PgpUtilities.GetDecoderStream(inputStream);

                var pgpObjectFactory = new PgpObjectFactory(decoderStream);

                var signatureList = (PgpSignatureList)pgpObjectFactory.NextPgpObject();
                var signature     = signatureList[0];

                var publicKeyRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(keyIn));
                var publicKey     = publicKeyRing.GetPublicKey(signature.KeyId);

                signature.InitVerify(publicKey);

                while ((chr = cleartextStream.ReadByte()) > 0)
                {
                    signature.Update((byte)chr);
                }
                cleartextStream.Position = 0;

                cleartextOut = cleartextStream;
                return(signature.Verify());
            }
            catch
            {
                cleartextOut = null;
                return(false);
            }
        }
        public override void PerformTest()
        {
            //
            // test immediate close
            //
            MemoryStream        bOut = new MemoryStream();
            ArmoredOutputStream aOut = new ArmoredOutputStream(bOut);

            aOut.Close();

            byte[] data = bOut.ToArray();

            if (data.Length != 0)
            {
                Fail("No data should have been written");
            }

            //
            // multiple close
            //
            bOut = new MemoryStream();
            aOut = new ArmoredOutputStream(bOut);

            aOut.Write(sample, 0, sample.Length);

            aOut.Close();
            aOut.Close();

            int mc = markerCount(bOut.ToArray());

            if (mc < 1)
            {
                Fail("No end marker found");
            }

            if (mc > 1)
            {
                Fail("More than one end marker found");
            }

            //
            // writing and reading single objects
            //
            bOut = new MemoryStream();
            aOut = new ArmoredOutputStream(bOut);

            aOut.Write(sample, 0, sample.Length);

            aOut.Close();

            ArmoredInputStream aIn = new ArmoredInputStream(
                new MemoryStream(bOut.ToArray(), false));

            PgpObjectFactory fact = new PgpObjectFactory(aIn);
            int count             = 0;

            while (fact.NextPgpObject() != null)
            {
                count++;
            }

            if (count != 1)
            {
                Fail("wrong number of objects found: " + count);
            }

            //
            // writing and reading multiple objects  - in single block
            //
            bOut = new MemoryStream();
            aOut = new ArmoredOutputStream(bOut);

            aOut.Write(sample, 0, sample.Length);
            aOut.Write(sample, 0, sample.Length);

            aOut.Close();

            aIn = new ArmoredInputStream(
                new MemoryStream(bOut.ToArray(), false));

            fact  = new PgpObjectFactory(aIn);
            count = 0;

            while (fact.NextPgpObject() != null)
            {
                count++;
            }

            if (count != 2)
            {
                Fail("wrong number of objects found: " + count);
            }

            //
            // writing and reading multiple objects  - in single block
            //
            bOut = new MemoryStream();
            aOut = new ArmoredOutputStream(bOut);

            aOut.Write(sample, 0, sample.Length);

            aOut.Close();                 // does not close underlying stream

            aOut = new ArmoredOutputStream(bOut);

            aOut.Write(sample, 0, sample.Length);

            aOut.Close();

            aIn = new ArmoredInputStream(
                new MemoryStream(bOut.ToArray(), false));

            count = 0;
            bool atLeastOne;

            do
            {
                atLeastOne = false;
                fact       = new PgpObjectFactory(aIn);

                while (fact.NextPgpObject() != null)
                {
                    atLeastOne = true;
                    count++;
                }
            }while (atLeastOne);

            if (count != 2)
            {
                Fail("wrong number of objects found: " + count);
            }

            blankLineTest();
            pgpUtilTest();
            repeatHeaderTest();
        }
		/*
		* verify a clear text signed file
		*/
        private static void VerifyFile(
            Stream	inputStream,
            Stream	keyIn,
			string	resultName)
        {
			ArmoredInputStream aIn = new ArmoredInputStream(inputStream);
			Stream outStr = File.Create(resultName);

			//
			// write out signed section using the local line separator.
			// note: trailing white space needs to be removed from the end of
			// each line RFC 4880 Section 7.1
			//
			MemoryStream lineOut = new MemoryStream();
			int lookAhead = ReadInputLine(lineOut, aIn);
			byte[] lineSep = LineSeparator;

			if (lookAhead != -1 && aIn.IsClearText())
			{
				byte[] line = lineOut.ToArray();
				outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line));
				outStr.Write(lineSep, 0, lineSep.Length);

				while (lookAhead != -1 && aIn.IsClearText())
				{
					lookAhead = ReadInputLine(lineOut, lookAhead, aIn);
                
					line = lineOut.ToArray();
					outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line));
					outStr.Write(lineSep, 0, lineSep.Length);
				}
			}
            else
            {
                // a single line file
                if (lookAhead != -1)
                {
                    byte[] line = lineOut.ToArray();
                    outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line));
                    outStr.Write(lineSep, 0, lineSep.Length);
                }
            }

			outStr.Close();

			PgpPublicKeyRingBundle pgpRings = new PgpPublicKeyRingBundle(keyIn);

			PgpObjectFactory pgpFact = new PgpObjectFactory(aIn);
			PgpSignatureList p3 = (PgpSignatureList) pgpFact.NextPgpObject();
			PgpSignature sig = p3[0];

			sig.InitVerify(pgpRings.GetPublicKey(sig.KeyId));

			//
			// read the input, making sure we ignore the last newline.
			//
			Stream sigIn = File.OpenRead(resultName);

			lookAhead = ReadInputLine(lineOut, sigIn);

			ProcessLine(sig, lineOut.ToArray());

			if (lookAhead != -1)
			{
				do
				{
					lookAhead = ReadInputLine(lineOut, lookAhead, sigIn);

					sig.Update((byte) '\r');
					sig.Update((byte) '\n');

					ProcessLine(sig, lineOut.ToArray());
				}
				while (lookAhead != -1);
			}

			sigIn.Close();

			if (sig.Verify())
            {
                Console.WriteLine("signature verified.");
            }
            else
            {
                Console.WriteLine("signature verification failed.");
            }
        }
Example #24
0
		public override void PerformTest()
		{
			//
			// test immediate close
			//
			MemoryStream bOut = new MemoryStream();
			ArmoredOutputStream aOut = new ArmoredOutputStream(bOut);

			aOut.Close();

			byte[] data = bOut.ToArray();

			if (data.Length != 0)
			{
				Fail("No data should have been written");
			}

			//
			// multiple close
			//
			bOut = new MemoryStream();
			aOut = new ArmoredOutputStream(bOut);

			aOut.Write(sample, 0, sample.Length);

			aOut.Close();
			aOut.Close();

			int mc = markerCount(bOut.ToArray());

			if (mc < 1)
			{
				Fail("No end marker found");
			}

			if (mc > 1)
			{
				Fail("More than one end marker found");
			}

			//
			// writing and reading single objects
			//
			bOut = new MemoryStream();
			aOut = new ArmoredOutputStream(bOut);

			aOut.Write(sample, 0, sample.Length);

			aOut.Close();

			ArmoredInputStream aIn = new ArmoredInputStream(
				new MemoryStream(bOut.ToArray(), false));

			PgpObjectFactory fact = new PgpObjectFactory(aIn);
			int count = 0;

			while (fact.NextPgpObject() != null)
			{
				count++;
			}

			if (count != 1)
			{
				Fail("wrong number of objects found: " + count);
			}

			//
			// writing and reading multiple objects  - in single block
			//
			bOut = new MemoryStream();
			aOut = new ArmoredOutputStream(bOut);

			aOut.Write(sample, 0, sample.Length);
			aOut.Write(sample, 0, sample.Length);

			aOut.Close();

			aIn = new ArmoredInputStream(
				new MemoryStream(bOut.ToArray(), false));

			fact = new PgpObjectFactory(aIn);
			count = 0;

			while (fact.NextPgpObject() != null)
			{
				count++;
			}

			if (count != 2)
			{
				Fail("wrong number of objects found: " + count);
			}

			//
			// writing and reading multiple objects  - in single block
			//
			bOut = new MemoryStream();
			aOut = new ArmoredOutputStream(bOut);

			aOut.Write(sample, 0, sample.Length);

			aOut.Close();     // does not close underlying stream

			aOut = new ArmoredOutputStream(bOut);

			aOut.Write(sample, 0, sample.Length);

			aOut.Close();

			aIn = new ArmoredInputStream(
				new MemoryStream(bOut.ToArray(), false));

			count = 0;
			bool atLeastOne;
			do
			{
				atLeastOne = false;
				fact = new PgpObjectFactory(aIn);

				while (fact.NextPgpObject() != null)
				{
					atLeastOne = true;
					count++;
				}
			}
			while (atLeastOne);

			if (count != 2)
			{
				Fail("wrong number of objects found: " + count);
			}

			blankLineTest();
		}
Example #25
0
		private void blankLineTest()
		{
			byte[] blankLineBytes = Encoding.ASCII.GetBytes(blankLineData);
			MemoryStream bIn = new MemoryStream(blankLineBytes, false);
			ArmoredInputStream aIn = new ArmoredInputStream(bIn, true);

			MemoryStream bOut = new MemoryStream();
			int c;
			while ((c = aIn.ReadByte()) >= 0)
			{
				bOut.WriteByte((byte)c);
			}

			byte[] expected = Encoding.ASCII.GetBytes("Hello World!");

			if (!Arrays.AreEqual(expected, bOut.ToArray()))
			{
				Fail("Incorrect message retrieved in blank line test.");
			}
		}
Example #26
0
        /// <summary>
        /// Verify signature for cleartext (e.g. emails)
        /// </summary>
        /// <param name="data">Data to verify</param>
        /// <returns>Return true if signature validates, else false.</returns>
        public bool VerifyClear(byte[] data)
        {
            Context = new CryptoContext(Context);

            var crlf     = new byte[] { (byte)'\r', (byte)'\n' };
            var encoding = ASCIIEncoding.UTF8;

            using (var dataIn = new MemoryStream(data))
                using (var armoredIn = new ArmoredInputStream(dataIn))
                {
                    if (!armoredIn.IsClearText())
                    {
                        throw new CryptoException("Error, message is not armored clear-text.");
                    }

                    var headers = armoredIn.GetArmorHeaders();
                    if (headers != null)
                    {
                        foreach (var header in headers)
                        {
                            if (Regex.IsMatch(header, @"Charset: ([^\s]*)"))
                            {
                                var encodingType = Regex.Match(header, @"Charset: ([^\s]*)").Groups[1].Value;
                                encoding = Encoding.GetEncoding(encodingType);
                            }
                        }
                    }

                    using (var clearOut = new MemoryStream())
                    {
                        using (var clearIn = new MemoryStream())
                        {
                            int ch = 0;
                            while ((ch = armoredIn.ReadByte()) >= 0 && armoredIn.IsClearText())
                            {
                                clearIn.WriteByte((byte)ch);
                            }

                            clearIn.Position = 0;

                            using (var stringIn = new StringReader(encoding.GetString(clearIn.ToArray())))
                            {
                                do
                                {
                                    var line = stringIn.ReadLine();
                                    if (line == null)
                                    {
                                        break;
                                    }

                                    line = line
                                           .TrimEnd(null)
                                           .TrimEnd(new char[] { ' ', '\t', '\n', '\r' })
                                           .TrimEnd(null)
                                           + "\r\n";

                                    var buff = encoding.GetBytes(line);
                                    clearOut.Write(buff, 0, buff.Length);
                                }while (true);
                            }
                        }

                        clearOut.Position = 0;

                        var factory       = new PgpObjectFactory(armoredIn);
                        var signatureList = (PgpSignatureList)factory.NextPgpObject();
                        var signature     = signatureList[0];

                        Context.IsEncrypted = false;
                        Context.IsSigned    = true;
                        Context.SignedBy    = GetPublicKey(signature.KeyId);

                        if (Context.SignedBy == null)
                        {
                            throw new PublicKeyNotFoundException("Public key not found for key id \"" + signature.KeyId + "\".");
                        }

                        signature.InitVerify(GetPublicKey(signature.KeyId));
                        signature.Update(clearOut.ToArray(), 0, (int)(clearOut.Length - 2));
                        Context.SignatureValidated = signature.Verify();

                        return(Context.SignatureValidated);
                    }
                }
        }