예제 #1
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));
        }
        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);
            }
        }
		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.");
            }
        }
예제 #5
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);
            }
        }
예제 #6
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);
                    }
                }
        }
		/*
		* 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.");
            }
        }
예제 #8
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);
        }
예제 #9
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);
        }
        /*
         * 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);
        }