/**
         * verify the signature in in against the file fileName.
         */
        private static bool VerifySignature(
            string OriginalMessage,
            string EncodedMessage,
            Stream keyIn)
        {
            byte[] bytes = Convert.FromBase64String(EncodedMessage);
            using (Stream inputStream = new MemoryStream(bytes))
            {
                PgpObjectFactory pgpFact = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream));
                PgpSignatureList p3      = null;
                PgpObject        o       = pgpFact.NextPgpObject();
                if (o is PgpCompressedData)
                {
                    PgpCompressedData c1 = (PgpCompressedData)o;
                    pgpFact = new PgpObjectFactory(c1.GetDataStream());

                    p3 = (PgpSignatureList)pgpFact.NextPgpObject();
                }
                else
                {
                    p3 = (PgpSignatureList)o;
                }

                PgpPublicKeyRingBundle pgpPubRingCollection = new PgpPublicKeyRingBundle(
                    PgpUtilities.GetDecoderStream(keyIn));
                PgpSignature sig = p3[0];
                PgpPublicKey key = pgpPubRingCollection.GetPublicKey(sig.KeyId);
                sig.InitVerify(key);
                sig.Update(System.Text.Encoding.UTF8.GetBytes(OriginalMessage));

                return(sig.Verify());
            }
        }
Ejemplo n.º 2
0
        private static void VerifySignature(PgpOnePassSignatureList onePassSigList, PgpSignatureList signatureList, PgpPublicKey pubKey, byte[] original)
        {
            PgpOnePassSignature ops = onePassSigList[0];

            ops.InitVerify(pubKey);
            ops.Update(original);

            PgpSignatureList p3  = signatureList;
            PgpSignature     sig = p3[0];

            if (sig.KeyId != pubKey.KeyId)
            {
                throw new PgpException("key id mismatch in signature.");
            }

            if (!ops.Verify(sig))
            {
                throw new PgpException("Failed generated signature check.");
            }

            sig.InitVerify(pubKey);

            for (int i = 0; i < original.Length; i++)
            {
                sig.Update(original[i]);
            }

            //sig.Update(original);

            if (!sig.Verify())
            {
                throw new PgpException("Failed generated signature check against original data.");
            }
        }
Ejemplo n.º 3
0
        private void doSigVerifyTest(
            string publicKeyFile,
            string sigFile)
        {
            PgpPublicKeyRing publicKey = loadPublicKey(publicKeyFile);
            PgpObjectFactory pgpFact   = loadSig(sigFile);

            PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject();

            pgpFact = new PgpObjectFactory(c1.GetDataStream());

            PgpOnePassSignatureList p1  = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
            PgpOnePassSignature     ops = p1[0];

            PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject();

            Stream dIn = p2.GetInputStream();

            ops.InitVerify(publicKey.GetPublicKey());

            int ch;

            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
            }

            PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject();

            Assert.IsTrue(ops.Verify(p3[0]));
        }
Ejemplo n.º 4
0
        public static bool VerifySignature(byte[] data, string signature, PgpPublicKey publicKey = null)
        {
            PgpSignatureList p3 = null;

            using (var inputStream = PgpUtilities.GetDecoderStream(Tools.GenerateStreamFromString(signature))) {
                var pgpFact = new PgpObjectFactory(inputStream);
                var o       = pgpFact.NextPgpObject();
                if (o is PgpCompressedData c1)
                {
                    pgpFact = new PgpObjectFactory(c1.GetDataStream());
                    p3      = (PgpSignatureList)pgpFact.NextPgpObject();
                }
                else
                {
                    p3 = (PgpSignatureList)o;
                }
            }

            var sig = p3[0];

            if (publicKey == null)
            {
                publicKey = masterSecretKey.PublicKey;
            }
            sig.InitVerify(publicKey);
            sig.Update(data);

            return(sig.Verify());
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Attempt to verify a PGP signed message using the matching public key.
        /// </summary>
        /// <param name="signedMessageStream">Stream containing the signed message.</param>
        /// <param name="signatureStream">Stream containing the signature.</param>
        /// <param name="publicKey">BouncyCastle public key to be used for verification.</param>
        /// <remarks>The message and signature should be passed in without ASCII Armor.</remarks>
        /// <returns>Whether the message's signature is verified.</returns>
        public static bool VerifySignature(Stream signedMessageStream, Stream signatureStream, PgpPublicKey publicKey)
        {
            // Decode from Base-64.
            using (Stream decoderStream = PgpUtilities.GetDecoderStream(signatureStream))
            {
                // Extract the signature list.
                PgpObjectFactory pgpObjectFactory = new PgpObjectFactory(decoderStream);

                PgpObject pgpObject = pgpObjectFactory.NextPgpObject();
                if (pgpObject is PgpSignatureList)
                {
                    PgpSignatureList signatureList = pgpObject as PgpSignatureList;

                    // Hydrate the signature object with the message to be verified.
                    PgpSignature signature = signatureList[0];
                    signature.InitVerify(publicKey);
                    signedMessageStream.Seek(0, SeekOrigin.Begin);
                    for (int i = 0; i < signedMessageStream.Length; i++)
                    {
                        signature.Update((byte)signedMessageStream.ReadByte());
                    }

                    // Return the result.
                    return(signature.Verify());
                }
                else
                {
                    return(false);
                }
            }
        }
Ejemplo n.º 6
0
        private void SetPgpSignature(SignatureTag tag, PgpSignature signature)
        {
            PgpSignatureList signatureList = new PgpSignatureList(signature);
            byte[] value = signature.GetEncoded();

            this.SetByteArray(tag, value);
        }
Ejemplo n.º 7
0
        /// <summary>
        ///     Verifies the specified signature using the specified public key.
        /// </summary>
        /// <param name="input">The signature to verify.</param>
        /// <param name="publicKey">The public key with which to decode the signature.</param>
        /// <returns>A byte array containing the message contained within the signature.</returns>
        /// <exception cref="PgpDataValidationException">
        ///     Thrown when the specified signature is invalid, or if an exception is encountered while validating.
        /// </exception>
        public static byte[] Verify(string input, string publicKey)
        {
            // create input streams from
            Stream inputStream     = new MemoryStream(Encoding.UTF8.GetBytes(input ?? string.Empty));
            Stream publicKeyStream = new MemoryStream(Encoding.UTF8.GetBytes(publicKey ?? string.Empty));

            // enclose all operations in a try/catch. if we encounter any exceptions verification fails.
            try
            {
                // lines taken pretty much verbatim from the bouncycastle example. not sure what it all does.
                inputStream = PgpUtilities.GetDecoderStream(inputStream);

                PgpObjectFactory  pgpFact = new PgpObjectFactory(inputStream);
                PgpCompressedData c1      = (PgpCompressedData)pgpFact.NextPgpObject();
                pgpFact = new PgpObjectFactory(c1.GetDataStream());

                PgpOnePassSignatureList p1  = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
                PgpOnePassSignature     ops = p1[0];

                PgpLiteralData         p2      = (PgpLiteralData)pgpFact.NextPgpObject();
                Stream                 dIn     = p2.GetInputStream();
                PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(publicKeyStream));
                PgpPublicKey           key     = pgpRing.GetPublicKey(ops.KeyId);

                // set up a memorystream to contain the message contained within the signature
                MemoryStream memoryStream = new MemoryStream();

                ops.InitVerify(key);

                int ch;
                while ((ch = dIn.ReadByte()) >= 0)
                {
                    ops.Update((byte)ch);
                    memoryStream.WriteByte((byte)ch);
                }

                // save the contents of the memorystream to a byte array
                byte[] retVal = memoryStream.ToArray();

                memoryStream.Close();

                PgpSignatureList p3       = (PgpSignatureList)pgpFact.NextPgpObject();
                PgpSignature     firstSig = p3[0];

                // verify.
                if (ops.Verify(firstSig))
                {
                    return(retVal);
                }
                else
                {
                    throw new PgpDataValidationException();
                }
            }
            catch (Exception)
            {
                throw new PgpDataValidationException();
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Verifies a PGP signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpVerifySignature Returns: Object {string FilePath, Boolean Verified}
        /// </summary>
        public static Result PGPVerifySignFile(Input input)
        {
            try
            {
                Stream inputStream = PgpUtilities.GetDecoderStream(File.OpenRead(input.InputFile));

                PgpObjectFactory        pgpFact = new PgpObjectFactory(inputStream);
                PgpOnePassSignatureList p1      = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
                PgpOnePassSignature     ops     = p1[0];

                PgpLiteralData         p2      = (PgpLiteralData)pgpFact.NextPgpObject();
                Stream                 dIn     = p2.GetInputStream();
                PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(File.OpenRead(input.PublicKeyFile)));
                PgpPublicKey           key     = pgpRing.GetPublicKey(ops.KeyId);

                string fosPath;
                if (String.IsNullOrWhiteSpace(input.OutputFolder))
                {
                    fosPath = Path.Combine(Path.GetDirectoryName(input.InputFile), p2.FileName);
                }
                else
                {
                    fosPath = Path.Combine(input.OutputFolder, p2.FileName);
                }
                Stream fos = File.Create(fosPath);

                ops.InitVerify(key);

                int ch;
                while ((ch = dIn.ReadByte()) >= 0)
                {
                    ops.Update((byte)ch);
                    fos.WriteByte((byte)ch);
                }
                fos.Close();

                PgpSignatureList p3       = (PgpSignatureList)pgpFact.NextPgpObject();
                PgpSignature     firstSig = p3[0];
                bool             verified = ops.Verify(firstSig);

                Result ret = new Result
                {
                    FilePath = fosPath,
                    Verified = verified
                };

                return(ret);
            }
            catch (Exception e)
            {
                Result ret = new Result
                {
                    FilePath = input.OutputFolder,
                    Verified = false
                };

                return(ret);
            }
        }
Ejemplo n.º 9
0
        private void verifySignature(
            byte[] encodedSig,
            HashAlgorithmTag hashAlgorithm,
            PgpPublicKey pubKey,
            byte[] original)
        {
            PgpObjectFactory        pgpFact = new PgpObjectFactory(encodedSig);
            PgpOnePassSignatureList p1      = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
            PgpOnePassSignature     ops     = p1[0];
            PgpLiteralData          p2      = (PgpLiteralData)pgpFact.NextPgpObject();
            Stream dIn = p2.GetInputStream();

            ops.InitVerify(pubKey);

            int ch;

            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
            }

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

            DateTime creationTime = sig.CreationTime;

            // Check creationTime is recent
            if (creationTime.CompareTo(DateTime.UtcNow) > 0 ||
                creationTime.CompareTo(DateTime.UtcNow.AddMinutes(-10)) < 0)
            {
                Fail("bad creation time in signature: " + creationTime);
            }

            if (sig.KeyId != pubKey.KeyId)
            {
                Fail("key id mismatch in signature");
            }

            if (!ops.Verify(sig))
            {
                Fail("Failed generated signature check - " + hashAlgorithm);
            }

            sig.InitVerify(pubKey);

            for (int i = 0; i != original.Length; i++)
            {
                sig.Update(original[i]);
            }

            sig.Update(original);

            if (!sig.Verify())
            {
                Fail("Failed generated signature check against original data");
            }
        }
Ejemplo n.º 10
0
        public static bool Verify(string hash, string signature, string publicKey)
        {
            try {
                var signatureStream = new MemoryStream(Encoding.ASCII.GetBytes(signature));
                var decoderStream   = PgpUtilities.GetDecoderStream(signatureStream);

                PgpObjectFactory pgpObjectFactory = new PgpObjectFactory(decoderStream);

                PgpOnePassSignatureList signatureList    = (PgpOnePassSignatureList)pgpObjectFactory.NextPgpObject();
                PgpOnePassSignature     onePassSignature = signatureList[0];

                PgpLiteralData         literalData   = (PgpLiteralData)pgpObjectFactory.NextPgpObject();
                Stream                 literalStream = literalData.GetInputStream();
                Stream                 keyFile       = new MemoryStream(Encoding.ASCII.GetBytes(publicKey));
                PgpPublicKeyRingBundle pgpRing       = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(keyFile));
                PgpPublicKey           key           = pgpRing.GetPublicKey(onePassSignature.KeyId);
                Stream                 outStream     = new MemoryStream();

                onePassSignature.InitVerify(key);

                int ch;
                while ((ch = literalStream.ReadByte()) >= 0)
                {
                    onePassSignature.Update((byte)ch);
                    outStream.WriteByte((byte)ch);
                }
                var hashStream = new MemoryStream(Encoding.ASCII.GetBytes(hash));
                outStream.Seek(0, SeekOrigin.Begin);
                if (hashStream.Length != outStream.Length)
                {
                    return(false);
                }
                int left, right;
                while ((left = hashStream.ReadByte()) >= 0 && (right = outStream.ReadByte()) >= 0)
                {
                    if (left != right)
                    {
                        return(false);
                    }
                }
                outStream.Dispose();

                PgpSignatureList signatureList2 = (PgpSignatureList)pgpObjectFactory.NextPgpObject();
                PgpSignature     firstSig       = signatureList2[0];
                if (onePassSignature.Verify(firstSig))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            } catch {
                return(false);
            }
        }
Ejemplo n.º 11
0
        public void Add(string hash, byte[] rawSignature)
        {
            using (MemoryStream stream = new MemoryStream(rawSignature))
                using (var signatureStream = PgpUtilities.GetDecoderStream(stream))
                {
                    PgpObjectFactory pgpFactory    = new PgpObjectFactory(signatureStream);
                    PgpSignatureList signatureList = (PgpSignatureList)pgpFactory.NextPgpObject();
                    PgpSignature     signature     = signatureList[0];

                    this.Signatures.Add(hash, signature);
                }
        }
Ejemplo n.º 12
0
        private void DoTestSignedEncMessage()
        {
            PgpObjectFactory pgpFact = new PgpObjectFactory(signedEncMessage);

            PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpFact.NextPgpObject();

            PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0];

            PgpPublicKeyRing publicKeyRing = new PgpPublicKeyRing(testPubKey);

            PgpPublicKey publicKey = publicKeyRing.GetPublicKey(encP.KeyId);

            PgpSecretKey secretKey = PgpSecretKey.ParseSecretKeyFromSExpr(new MemoryStream(sExprKeySub, false),
                                                                          "test".ToCharArray(), publicKey);

            Stream clear = encP.GetDataStream(secretKey.ExtractPrivateKey(null));

            PgpObjectFactory plainFact = new PgpObjectFactory(clear);

            PgpCompressedData cData = (PgpCompressedData)plainFact.NextPgpObject();

            PgpObjectFactory compFact = new PgpObjectFactory(cData.GetDataStream());

            PgpOnePassSignatureList sList = (PgpOnePassSignatureList)compFact.NextPgpObject();

            PgpOnePassSignature ops = sList[0];

            PgpLiteralData lData = (PgpLiteralData)compFact.NextPgpObject();

            if (!"test.txt".Equals(lData.FileName))
            {
                Fail("wrong file name detected");
            }

            Stream dIn = lData.GetInputStream();

            ops.InitVerify(publicKeyRing.GetPublicKey(ops.KeyId));

            int ch;

            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
            }

            PgpSignatureList p3 = (PgpSignatureList)compFact.NextPgpObject();

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed signature check");
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Gets a PGP signature.
        /// </summary>
        /// <param name="tag">
        /// The tag which contains the PGP signature.
        /// </param>
        /// <returns>
        /// A <see cref="PgpSignature"/> object which represents the PGP signature.
        /// </returns>
        private PgpSignature GetPgpSignature(SignatureTag tag)
        {
            byte[] value = (byte[])this.Package.Signature.Records[tag].Value;

            using (MemoryStream stream = new MemoryStream(value))
            using (var signatureStream = PgpUtilities.GetDecoderStream(stream))
            {
                PgpObjectFactory pgpFactory = new PgpObjectFactory(signatureStream);
                PgpSignatureList signatureList = (PgpSignatureList)pgpFactory.NextPgpObject();
                PgpSignature signature = signatureList[0];
                return signature;
            }
        }
Ejemplo n.º 14
0
        /**
         * verify the signature in in against the file fileName.
         */
        private static void VerifySignature(
            string fileName,
            Stream inputStream,
            Stream keyIn)
        {
            inputStream = PgpUtilities.GetDecoderStream(inputStream);

            PgpObjectFactory pgpFact = new PgpObjectFactory(inputStream);
            PgpSignatureList p3      = null;
            PgpObject        o       = pgpFact.NextPgpObject();

            if (o is PgpCompressedData)
            {
                PgpCompressedData c1 = (PgpCompressedData)o;
                pgpFact = new PgpObjectFactory(c1.GetDataStream());

                p3 = (PgpSignatureList)pgpFact.NextPgpObject();
            }
            else
            {
                p3 = (PgpSignatureList)o;
            }

            PgpPublicKeyRingBundle pgpPubRingCollection = new PgpPublicKeyRingBundle(
                PgpUtilities.GetDecoderStream(keyIn));
            Stream       dIn = File.OpenRead(fileName);
            PgpSignature sig = p3[0];
            PgpPublicKey key = pgpPubRingCollection.GetPublicKey(sig.KeyId);

            sig.InitVerify(key);

            int ch;

            while ((ch = dIn.ReadByte()) >= 0)
            {
                sig.Update((byte)ch);
            }

            dIn.Close();

            if (sig.Verify())
            {
                Console.WriteLine("signature verified.");
            }
            else
            {
                Console.WriteLine("signature verification failed.");
            }
        }
Ejemplo n.º 15
0
        /*.......................................................................檔案數認證開始*/

        /*首先傳送端將訊息經過雜湊演算法計算後得到一個雜湊值,再利用它的私有鑰匙向雜湊值加密成為一個數位簽章(DS),接著,再將數位簽章附加在訊息後面一併傳送出去;
         * 接收端收到訊息之後,以同樣的雜湊演算計算出雜湊值(H’),並利用傳送端的公開鑰匙將 DS 解密,得到另一端的雜湊值(H)。
         * 接著,比較兩個雜湊值,如果相同的話,則可以確定該訊息的『完整性』(雜湊值相同),此外也可以確定其『不可否認性』(私有鑰匙與公開鑰匙配對)。*/

        /*
         * 簽章後的hash值 -> 公鑰(對方)解密 -> hash值
         * 解密後的文章 -> hash -> 解密後文章的hash值
         */


        private static void VerifyFile(
            Stream inputStream,   //預計數位認證原始檔案的資料流
            Stream keyIn,         //簽名方(對方)公鑰的資料流
            string outputFileName //預計匯出(數位認證後檔案)的完整路徑
            )
        {
            inputStream = PgpUtilities.GetDecoderStream(inputStream); //串流陣列化 byte Array
            PgpObjectFactory pgpFact = new PgpObjectFactory(inputStream);

            PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject();

            pgpFact = new PgpObjectFactory(c1.GetDataStream()); //解壓縮
            PgpOnePassSignatureList p1  = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
            PgpOnePassSignature     ops = p1[0];
            PgpLiteralData          p2  = (PgpLiteralData)pgpFact.NextPgpObject();
            Stream dIn = p2.GetInputStream();

            PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(keyIn));
            PgpPublicKey           key     = pgpRing.GetPublicKey(ops.KeyId); //取出公鑰

            Stream fileOutput = File.Create(outputFileName);                  //預計匯出檔案建立

            ops.InitVerify(key);                                              //驗證公鑰是否符合
            int ch;

            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);           //進行解密
                fileOutput.WriteByte((byte)ch); //寫入預計匯出檔案
            }
            fileOutput.Close();
            fileOutput.Dispose();

            PgpSignatureList p3       = (PgpSignatureList)pgpFact.NextPgpObject();
            PgpSignature     firstSig = p3[0];

            if (ops.Verify(firstSig)) //Hash值比較
            {
                Console.Out.WriteLine("signature verified.");
            }
            else
            {
                Console.Out.WriteLine("signature verification failed.");
            }
        }
        /**
         * verify the passed in file as being correctly signed.
         */
        private static void VerifyFile(
            Stream inputStream,
            Stream keyIn)
        {
            inputStream = PgpUtilities.GetDecoderStream(inputStream);

            PgpObjectFactory  pgpFact = new PgpObjectFactory(inputStream);
            PgpCompressedData c1      = (PgpCompressedData)pgpFact.NextPgpObject();

            pgpFact = new PgpObjectFactory(c1.GetDataStream());

            PgpOnePassSignatureList p1  = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
            PgpOnePassSignature     ops = p1[0];

            PgpLiteralData         p2      = (PgpLiteralData)pgpFact.NextPgpObject();
            Stream                 dIn     = p2.GetInputStream();
            PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(keyIn));
            IPgpPublicKey          key     = pgpRing.GetPublicKey(ops.KeyId);
            Stream                 fos     = File.Create(p2.FileName);

            ops.InitVerify(key);

            int ch;

            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
                fos.WriteByte((byte)ch);
            }
            fos.Close();

            PgpSignatureList p3       = (PgpSignatureList)pgpFact.NextPgpObject();
            PgpSignature     firstSig = p3[0];

            if (ops.Verify(firstSig))
            {
                Console.Out.WriteLine("signature verified.");
            }
            else
            {
                Console.Out.WriteLine("signature verification failed.");
            }
        }
Ejemplo n.º 17
0
        public bool VerifyAsStringSignature(string data, string signature, PgpPublicKey publicKey = null)
        {
            PgpSignatureList p3 = null;

            signature = Tools.SignatureFix(signature);
            using (var inputStream = PgpUtilities.GetDecoderStream(Tools.GenerateStreamFromString(signature))) {
                var pgpFact = new PgpObjectFactory(inputStream);
                var o       = pgpFact.NextPgpObject();
                if (o is PgpCompressedData c1)
                {
                    pgpFact = new PgpObjectFactory(c1.GetDataStream());
                    p3      = (PgpSignatureList)pgpFact.NextPgpObject();
                }
                else
                {
                    p3 = (PgpSignatureList)o;
                }
            }

            var sig = p3[0];

            if (publicKey == null)
            {
                string keyId       = sig.KeyId.ToString("X").ToUpper();
                string fingerPrint = keyId.Length < 16 ? Tools.H8FP(keyId) : Tools.H16FP(sig.KeyId.ToString("X").ToUpper());
                publicKey = krm[fingerPrint];
                if (publicKey == null)
                {
                    throw new KeyNotLoadedException(fingerPrint);
                }
            }
            sig.InitVerify(publicKey);
            sig.Update(Encoding.UTF8.GetBytes(data));

            return(sig.Verify());
        }
Ejemplo n.º 18
0
        public static byte[] Decrypt2(byte[] encryptedData, RetrievePgpKeys keys, AlgorithmAgreement agreed)
        {
            Stream inputStream = new MemoryStream(encryptedData);

            inputStream = PgpUtilities.GetDecoderStream(inputStream);

            PgpObjectFactory     pgpObjFactory = new PgpObjectFactory(inputStream);
            PgpEncryptedDataList enc;
            PgpObject            pgpObj = pgpObjFactory.NextPgpObject();

            if (pgpObj is PgpEncryptedDataList)
            {
                enc = (PgpEncryptedDataList)pgpObj;
            }
            else
            {
                enc = (PgpEncryptedDataList)pgpObjFactory.NextPgpObject();
            }

            PgpPrivateKey             privKey = keys.PrivateKey;
            PgpPublicKeyEncryptedData pbe     = null;

            foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
            {
                if (privKey != null)
                {
                    pbe = pked;
                    break;
                }
            }
            PgpOnePassSignatureList onePassSigList = null;
            PgpSignatureList        signatureList  = null;
            PgpLiteralData          literalData    = null;
            Stream           clear        = pbe.GetDataStream(privKey);
            PgpObjectFactory plainFactory = new PgpObjectFactory(clear);
            PgpObject        message      = plainFactory.NextPgpObject();

            if (message is PgpCompressedData)
            {
                PgpCompressedData compressedData = (PgpCompressedData)message;
                Stream            compDataIn     = compressedData.GetDataStream();
                PgpObjectFactory  objectFactory  = new PgpObjectFactory(compDataIn);
                message = objectFactory.NextPgpObject();
                if (message is PgpOnePassSignatureList)
                {
                    onePassSigList = (message as PgpOnePassSignatureList);

                    message = objectFactory.NextPgpObject();
                    if (message is PgpLiteralData)
                    {
                        literalData = (PgpLiteralData)message;
                    }
                    message = objectFactory.NextPgpObject();
                    if (message is PgpSignatureList)
                    {
                        signatureList = (PgpSignatureList)message;
                    }
                }
                compDataIn.Close();
            }
            else
            {
                if (message is PgpOnePassSignatureList)
                {
                    onePassSigList = (message as PgpOnePassSignatureList);
                }
                message = plainFactory.NextPgpObject();
                if (message is PgpLiteralData)
                {
                    literalData = (PgpLiteralData)message;
                }
                message = plainFactory.NextPgpObject();
                if (message is PgpSignatureList)
                {
                    signatureList = (PgpSignatureList)message;
                }
            }

            Stream unc = literalData.GetInputStream();

            byte[] returnBytes = Org.BouncyCastle.Utilities.IO.Streams.ReadAll(unc);

            if (onePassSigList != null && signatureList != null)
            {
                VerifySignature(onePassSigList, signatureList, keys.SecretKey.PublicKey, returnBytes);
            }

            unc.Close();
            clear.Close();
            inputStream.Close();

            return(returnBytes);
        }
        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);
            }
        }
Ejemplo n.º 20
0
        public static byte[] Decrypt(byte[] encryptedData, RetrievePgpKeys keys, AlgorithmAgreement agreed)
        {
            Stream inputStream = new MemoryStream(encryptedData);

            inputStream = PgpUtilities.GetDecoderStream(inputStream);

            PgpObjectFactory     pgpObjFactory = new PgpObjectFactory(inputStream);
            PgpEncryptedDataList enc;
            PgpObject            pgpObj = pgpObjFactory.NextPgpObject();

            if (pgpObj is PgpEncryptedDataList)
            {
                enc = (PgpEncryptedDataList)pgpObj;
            }
            else
            {
                enc = (PgpEncryptedDataList)pgpObjFactory.NextPgpObject();
            }

            PgpPrivateKey             privKey = keys.PrivateKey;
            PgpPublicKeyEncryptedData pbe     = null;

            foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
            {
                if (privKey != null)
                {
                    pbe = pked;
                    break;
                }
            }
            PgpOnePassSignatureList onePassSigList = null;
            PgpSignatureList        signatureList  = null;
            PgpLiteralData          literalData    = null;

            byte[]           returnBytes  = null;
            Stream           clear        = pbe.GetDataStream(privKey);
            PgpObjectFactory plainFactory = new PgpObjectFactory(clear);

            for (; ;)
            {
                PgpObject message = plainFactory.NextPgpObject();
                if (message == null)
                {
                    break;
                }
                if (message is PgpCompressedData)
                {
                    PgpCompressedData compressedData = (PgpCompressedData)message;
                    plainFactory = new PgpObjectFactory(compressedData.GetDataStream());
                }
                else if (message is PgpLiteralData)
                {
                    literalData = (PgpLiteralData)message;
                    Stream unc = literalData.GetInputStream();
                    returnBytes = Org.BouncyCastle.Utilities.IO.Streams.ReadAll(unc);
                    unc.Close();
                }
                else if (message is PgpOnePassSignatureList)
                {
                    onePassSigList = (PgpOnePassSignatureList)message;
                }
                else if (message is PgpSignatureList)
                {
                    signatureList = (PgpSignatureList)message;
                }
                else if (message is PgpMarker)
                {
                }
                else
                {
                    throw new PgpException("message contains unknown message type.");
                }
            }
            //Stream unc = literalData.GetInputStream();

            //byte[] returnBytes = Org.BouncyCastle.Utilities.IO.Streams.ReadAll(unc);

            if ((onePassSigList != null) && (signatureList != null))
            {
                VerifySignature(onePassSigList, signatureList, keys.SecretKey.PublicKey, returnBytes);
            }

            //unc.Close();
            clear.Close();
            inputStream.Close();

            return(returnBytes);
        }
Ejemplo n.º 21
0
        public override void PerformTest()
        {
            PgpPublicKey pubKey = null;

            //
            // Read the public key
            //
            PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey);

            pubKey = pgpPub.GetPublicKey();

            //
            // Read the private key
            //
            PgpSecretKeyRing sKey       = new PgpSecretKeyRing(testPrivKey);
            PgpSecretKey     secretKey  = sKey.GetSecretKey();
            PgpPrivateKey    pgpPrivKey = secretKey.ExtractPrivateKey(pass);

            //
            // test signature message
            //
            PgpObjectFactory  pgpFact = new PgpObjectFactory(sig1);
            PgpCompressedData c1      = (PgpCompressedData)pgpFact.NextPgpObject();

            pgpFact = new PgpObjectFactory(c1.GetDataStream());

            PgpOnePassSignatureList p1  = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
            PgpOnePassSignature     ops = p1[0];

            PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject();

            Stream dIn = p2.GetInputStream();

            ops.InitVerify(pubKey);

            int ch;

            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
            }

            PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject();

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed signature check");
            }

            //
            // signature generation
            //
            GenerateTest(sKey, pubKey, pgpPrivKey);

            //
            // signature generation - canonical text
            //
            const string data = "hello world!";

            byte[]                dataBytes = Encoding.ASCII.GetBytes(data);
            MemoryStream          bOut      = new MemoryStream();
            MemoryStream          testIn    = new MemoryStream(dataBytes, false);
            PgpSignatureGenerator sGen      = new PgpSignatureGenerator(
                PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey);

            PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator(
                CompressionAlgorithmTag.Zip);

            BcpgOutputStream bcOut = new BcpgOutputStream(cGen.Open(new UncloseableStream(bOut)));

            sGen.GenerateOnePassVersion(false).Encode(bcOut);

            PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();
            DateTime testDateTime        = new DateTime(1973, 7, 27);
            Stream   lOut = lGen.Open(
                new UncloseableStream(bcOut),
                PgpLiteralData.Text,
                "_CONSOLE",
                dataBytes.Length,
                testDateTime);

            while ((ch = testIn.ReadByte()) >= 0)
            {
                lOut.WriteByte((byte)ch);
                sGen.Update((byte)ch);
            }

            lGen.Close();

            sGen.Generate().Encode(bcOut);

            cGen.Close();

            //
            // verify Generated signature - canconical text
            //
            pgpFact = new PgpObjectFactory(bOut.ToArray());

            c1 = (PgpCompressedData)pgpFact.NextPgpObject();

            pgpFact = new PgpObjectFactory(c1.GetDataStream());

            p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();

            ops = p1[0];

            p2 = (PgpLiteralData)pgpFact.NextPgpObject();
            if (!p2.ModificationTime.Equals(testDateTime))
            {
                Fail("Modification time not preserved");
            }

            dIn = p2.GetInputStream();

            ops.InitVerify(pubKey);

            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
            }

            p3 = (PgpSignatureList)pgpFact.NextPgpObject();

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed generated signature check");
            }

            //
            // Read the public key with user attributes
            //
            pgpPub = new PgpPublicKeyRing(testPubWithUserAttr);

            pubKey = pgpPub.GetPublicKey();

            int count = 0;

            foreach (PgpUserAttributeSubpacketVector attributes in pubKey.GetUserAttributes())
            {
                int sigCount = 0;
                foreach (object sigs in pubKey.GetSignaturesForUserAttribute(attributes))
                {
                    if (sigs == null)
                    {
                        Fail("null signature found");
                    }

                    sigCount++;
                }

                if (sigCount != 1)
                {
                    Fail("Failed user attributes signature check");
                }

                count++;
            }

            if (count != 1)
            {
                Fail("Failed user attributes check");
            }

            byte[] pgpPubBytes = pgpPub.GetEncoded();
            pgpPub = new PgpPublicKeyRing(pgpPubBytes);
            pubKey = pgpPub.GetPublicKey();
            count  = 0;

            foreach (object ua in pubKey.GetUserAttributes())
            {
                if (ua == null)
                {
                    Fail("null user attribute found");
                }

                count++;
            }

            if (count != 1)
            {
                Fail("Failed user attributes reread");
            }

            //
            // reading test extra data - key with edge condition for DSA key password.
            //
            char[] passPhrase = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

            sKey       = new PgpSecretKeyRing(testPrivKey2);
            pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(passPhrase);

            //
            // reading test - aes256 encrypted passphrase.
            //
            sKey       = new PgpSecretKeyRing(aesSecretKey);
            pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass);

            //
            // reading test - twofish encrypted passphrase.
            //
            sKey       = new PgpSecretKeyRing(twofishSecretKey);
            pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass);

            //
            // use of PgpKeyPair
            //
            DsaParametersGenerator pGen = new DsaParametersGenerator();

            pGen.Init(512, 80, new SecureRandom()); // TODO Is the certainty okay?
            DsaParameters dsaParams = pGen.GenerateParameters();
            DsaKeyGenerationParameters        kgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams);
            IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("DSA");

            kpg.Init(kgp);


            AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();

            PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.Dsa,
                                              kp.Public, kp.Private, DateTime.UtcNow);

            PgpPublicKey  k1 = pgpKp.PublicKey;
            PgpPrivateKey k2 = pgpKp.PrivateKey;
        }
Ejemplo n.º 22
0
        /**
         * Generated signature test
         *
         * @param sKey
         * @param pgpPrivKey
         * @return test result
         */
        public void GenerateTest(
            PgpSecretKeyRing sKey,
            PgpPublicKey pgpPubKey,
            PgpPrivateKey pgpPrivKey)
        {
            string       data = "hello world!";
            MemoryStream bOut = new MemoryStream();

            byte[]       dataBytes = Encoding.ASCII.GetBytes(data);
            MemoryStream testIn    = new MemoryStream(dataBytes, false);

            PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

            PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();

            IEnumerator enumerator = sKey.GetSecretKey().PublicKey.GetUserIds().GetEnumerator();

            enumerator.MoveNext();
            string primaryUserId = (string)enumerator.Current;

            spGen.SetSignerUserId(true, primaryUserId);

            sGen.SetHashedSubpackets(spGen.Generate());

            PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator(
                CompressionAlgorithmTag.Zip);

            BcpgOutputStream bcOut = new BcpgOutputStream(cGen.Open(new UncloseableStream(bOut)));

            sGen.GenerateOnePassVersion(false).Encode(bcOut);

            PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();

            DateTime testDateTime = new DateTime(1973, 7, 27);
            Stream   lOut         = lGen.Open(
                new UncloseableStream(bcOut),
                PgpLiteralData.Binary,
                "_CONSOLE",
                dataBytes.Length,
                testDateTime);

            int ch;

            while ((ch = testIn.ReadByte()) >= 0)
            {
                lOut.WriteByte((byte)ch);
                sGen.Update((byte)ch);
            }

            lGen.Close();

            sGen.Generate().Encode(bcOut);

            cGen.Close();

            PgpObjectFactory  pgpFact = new PgpObjectFactory(bOut.ToArray());
            PgpCompressedData c1      = (PgpCompressedData)pgpFact.NextPgpObject();

            pgpFact = new PgpObjectFactory(c1.GetDataStream());

            PgpOnePassSignatureList p1  = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
            PgpOnePassSignature     ops = p1[0];

            PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject();

            if (!p2.ModificationTime.Equals(testDateTime))
            {
                Fail("Modification time not preserved");
            }

            Stream dIn = p2.GetInputStream();

            ops.InitVerify(pgpPubKey);

            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
            }

            PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject();

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed generated signature check");
            }
        }
        /*
         * 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.");
            }
        }
        /// <summary>
        /// Verifies a PGP signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpVerifySignature Returns: Object {string FilePath, Boolean Verified}
        /// </summary>
        public static Result PGPVerifySignFile(Input input)
        {
            using (var inputStream = PgpUtilities.GetDecoderStream(File.OpenRead(input.InputFile)))
                using (var keyStream = PgpUtilities.GetDecoderStream(File.OpenRead(input.PublicKeyFile)))
                {
                    PgpObjectFactory        pgpFact          = new PgpObjectFactory(inputStream);
                    PgpOnePassSignatureList signatureList    = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
                    PgpOnePassSignature     onePassSignature = signatureList[0];

                    PgpLiteralData         p2      = (PgpLiteralData)pgpFact.NextPgpObject();
                    Stream                 dataIn  = p2.GetInputStream();
                    PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(keyStream);
                    PgpPublicKey           key     = pgpRing.GetPublicKey(onePassSignature.KeyId);

                    string outputPath;
                    if (String.IsNullOrWhiteSpace(input.OutputFolder))
                    {
                        outputPath = Path.Combine(Path.GetDirectoryName(input.InputFile), p2.FileName);
                    }
                    else
                    {
                        outputPath = Path.Combine(input.OutputFolder, p2.FileName);
                    }
                    using (var outputStream = File.Create(outputPath))
                    {
                        onePassSignature.InitVerify(key);

                        int ch;
                        while ((ch = dataIn.ReadByte()) >= 0)
                        {
                            onePassSignature.Update((byte)ch);
                            outputStream.WriteByte((byte)ch);
                        }
                        outputStream.Close();
                    }

                    bool verified;
                    // Will throw Exception if file is altered
                    try
                    {
                        PgpSignatureList p3       = (PgpSignatureList)pgpFact.NextPgpObject();
                        PgpSignature     firstSig = p3[0];
                        verified = onePassSignature.Verify(firstSig);
                    }
                    catch (Exception)
                    {
                        Result retError = new Result
                        {
                            FilePath = input.OutputFolder,
                            Verified = false
                        };

                        return(retError);
                    }

                    Result ret = new Result
                    {
                        FilePath = outputPath,
                        Verified = verified
                    };

                    return(ret);
                }
        }
        public override void PerformTest()
        {
            //
            // Read the public key
            //
            PgpObjectFactory pgpFact = new PgpObjectFactory(testPubKeyRing);
            PgpPublicKeyRing pgpPub  = (PgpPublicKeyRing)pgpFact.NextPgpObject();

            var pubKey = pgpPub.GetPublicKey();

            if (pubKey.BitStrength != 1024)
            {
                Fail("failed - key strength reported incorrectly.");
            }

            //
            // Read the private key
            //
            PgpSecretKeyRing sKey       = new PgpSecretKeyRing(testPrivKeyRing);
            IPgpSecretKey    secretKey  = sKey.GetSecretKey();
            IPgpPrivateKey   pgpPrivKey = secretKey.ExtractPrivateKey(pass);

            //
            // signature generation
            //
            const string data = "hello world!";

            byte[]                dataBytes = Encoding.ASCII.GetBytes(data);
            MemoryStream          bOut      = new MemoryStream();
            MemoryStream          testIn    = new MemoryStream(dataBytes, false);
            PgpSignatureGenerator sGen      = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa,
                                                                        HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

            PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator(
                CompressionAlgorithmTag.Zip);

            BcpgOutputStream bcOut = new BcpgOutputStream(
                cGen.Open(new UncloseableStream(bOut)));

            sGen.GenerateOnePassVersion(false).Encode(bcOut);

            PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();

            DateTime testDateTime = new DateTime(1973, 7, 27);
            Stream   lOut         = lGen.Open(
                new UncloseableStream(bcOut),
                PgpLiteralData.Binary,
                "_CONSOLE",
                dataBytes.Length,
                testDateTime);

            int ch;

            while ((ch = testIn.ReadByte()) >= 0)
            {
                lOut.WriteByte((byte)ch);
                sGen.Update((byte)ch);
            }

            lGen.Close();

            sGen.Generate().Encode(bcOut);

            cGen.Close();

            //
            // verify Generated signature
            //
            pgpFact = new PgpObjectFactory(bOut.ToArray());

            PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject();

            pgpFact = new PgpObjectFactory(c1.GetDataStream());

            PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();

            PgpOnePassSignature ops = p1[0];

            PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject();

            if (!p2.ModificationTime.Equals(testDateTime))
            {
                Fail("Modification time not preserved");
            }

            Stream dIn = p2.GetInputStream();

            ops.InitVerify(pubKey);

            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
            }

            PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject();

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed Generated signature check");
            }

            //
            // test encryption
            //

            //
            // find a key sutiable for encryption
            //
            long pgpKeyID = 0;
            IAsymmetricKeyParameter pKey = null;

            foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys())
            {
                if (pgpKey.Algorithm == PublicKeyAlgorithmTag.ElGamalEncrypt ||
                    pgpKey.Algorithm == PublicKeyAlgorithmTag.ElGamalGeneral)
                {
                    pKey     = pgpKey.GetKey();
                    pgpKeyID = pgpKey.KeyId;
                    if (pgpKey.BitStrength != 1024)
                    {
                        Fail("failed - key strength reported incorrectly.");
                    }

                    //
                    // verify the key
                    //
                }
            }

            IBufferedCipher c = CipherUtilities.GetCipher("ElGamal/None/PKCS1Padding");

            c.Init(true, pKey);

            byte[] inBytes  = Encoding.ASCII.GetBytes("hello world");
            byte[] outBytes = c.DoFinal(inBytes);

            pgpPrivKey = sKey.GetSecretKey(pgpKeyID).ExtractPrivateKey(pass);

            c.Init(false, pgpPrivKey.Key);

            outBytes = c.DoFinal(outBytes);

            if (!Arrays.AreEqual(inBytes, outBytes))
            {
                Fail("decryption failed.");
            }

            //
            // encrypted message
            //
            byte[] text = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o',
                            (byte)' ', (byte)'w', (byte)'o', (byte)'r', (byte)'l',(byte)'d',  (byte)'!', (byte)'\n' };

            PgpObjectFactory pgpF = new PgpObjectFactory(encMessage);

            PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

            PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0];

            Stream clear = encP.GetDataStream(pgpPrivKey);

            pgpFact = new PgpObjectFactory(clear);

            c1 = (PgpCompressedData)pgpFact.NextPgpObject();

            pgpFact = new PgpObjectFactory(c1.GetDataStream());

            PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject();

            if (!ld.FileName.Equals("test.txt"))
            {
                throw new Exception("wrong filename in packet");
            }

            Stream inLd = ld.GetDataStream();

            byte[] bytes = Streams.ReadAll(inLd);

            if (!Arrays.AreEqual(bytes, text))
            {
                Fail("wrong plain text in decrypted packet");
            }

            //
            // signed and encrypted message
            //
            pgpF = new PgpObjectFactory(signedAndEncMessage);

            encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

            encP = (PgpPublicKeyEncryptedData)encList[0];

            clear = encP.GetDataStream(pgpPrivKey);

            pgpFact = new PgpObjectFactory(clear);

            c1 = (PgpCompressedData)pgpFact.NextPgpObject();

            pgpFact = new PgpObjectFactory(c1.GetDataStream());

            p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();

            ops = p1[0];

            ld = (PgpLiteralData)pgpFact.NextPgpObject();

            bOut = new MemoryStream();

            if (!ld.FileName.Equals("test.txt"))
            {
                throw new Exception("wrong filename in packet");
            }

            inLd = ld.GetDataStream();

            //
            // note: we use the DSA public key here.
            //
            ops.InitVerify(pgpPub.GetPublicKey());

            while ((ch = inLd.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
                bOut.WriteByte((byte)ch);
            }

            p3 = (PgpSignatureList)pgpFact.NextPgpObject();

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed signature check");
            }

            if (!Arrays.AreEqual(bOut.ToArray(), text))
            {
                Fail("wrong plain text in decrypted packet");
            }

            //
            // encrypt
            //
            MemoryStream cbOut            = new MemoryStream();
            PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(
                SymmetricKeyAlgorithmTag.TripleDes, random);
            IPgpPublicKey puK = sKey.GetSecretKey(pgpKeyID).PublicKey;

            cPk.AddMethod(puK);

            Stream cOut = cPk.Open(new UncloseableStream(cbOut), bOut.ToArray().Length);

            cOut.Write(text, 0, text.Length);

            cOut.Close();

            pgpF = new PgpObjectFactory(cbOut.ToArray());

            encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

            encP = (PgpPublicKeyEncryptedData)encList[0];

            pgpPrivKey = sKey.GetSecretKey(pgpKeyID).ExtractPrivateKey(pass);

            clear    = encP.GetDataStream(pgpPrivKey);
            outBytes = Streams.ReadAll(clear);

            if (!Arrays.AreEqual(outBytes, text))
            {
                Fail("wrong plain text in Generated packet");
            }

            //
            // use of PgpKeyPair
            //
            IBigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
            IBigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);

            ElGamalParameters elParams = new ElGamalParameters(p, g);

            IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL");

            kpg.Init(new ElGamalKeyGenerationParameters(random, elParams));

            IAsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();

            PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.ElGamalGeneral,
                                              kp.Public, kp.Private, DateTime.UtcNow);

            PgpPublicKey  k1 = pgpKp.PublicKey;
            PgpPrivateKey k2 = pgpKp.PrivateKey;



            // Test bug with ElGamal P size != 0 mod 8 (don't use these sizes at home!)
            for (int pSize = 257; pSize < 264; ++pSize)
            {
                // Generate some parameters of the given size
                ElGamalParametersGenerator epg = new ElGamalParametersGenerator();
                epg.Init(pSize, 2, random);

                elParams = epg.GenerateParameters();

                kpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL");
                kpg.Init(new ElGamalKeyGenerationParameters(random, elParams));


                // Run a short encrypt/decrypt test with random key for the given parameters
                kp = kpg.GenerateKeyPair();

                PgpKeyPair elGamalKeyPair = new PgpKeyPair(
                    PublicKeyAlgorithmTag.ElGamalGeneral, kp, DateTime.UtcNow);

                cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, random);

                puK = elGamalKeyPair.PublicKey;

                cPk.AddMethod(puK);

                cbOut = new MemoryStream();

                cOut = cPk.Open(new UncloseableStream(cbOut), text.Length);

                cOut.Write(text, 0, text.Length);

                cOut.Close();

                pgpF = new PgpObjectFactory(cbOut.ToArray());

                encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

                encP = (PgpPublicKeyEncryptedData)encList[0];

                pgpPrivKey = elGamalKeyPair.PrivateKey;

                // Note: This is where an exception would be expected if the P size causes problems
                clear = encP.GetDataStream(pgpPrivKey);
                byte[] decText = Streams.ReadAll(clear);

                if (!Arrays.AreEqual(text, decText))
                {
                    Fail("decrypted message incorrect");
                }
            }


            // check sub key encoding

            foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys())
            {
                if (!pgpKey.IsMasterKey)
                {
                    byte[] kEnc = pgpKey.GetEncoded();

                    PgpObjectFactory objF = new PgpObjectFactory(kEnc);

                    // TODO Make PgpPublicKey a PgpObject or return a PgpPublicKeyRing
//					PgpPublicKey k = (PgpPublicKey)objF.NextPgpObject();
//
//					pKey = k.GetKey();
//					pgpKeyID = k.KeyId;
//					if (k.BitStrength != 1024)
//					{
//						Fail("failed - key strength reported incorrectly.");
//					}
//
//					if (objF.NextPgpObject() != null)
//					{
//						Fail("failed - stream not fully parsed.");
//					}
                }
            }
        }
Ejemplo n.º 26
0
        /*
         * decrypt a given stream.
         */

        public static void Decrypt(Stream inputStream, Stream privateKeyStream, string passPhrase, string outputFile, Stream publicKeyStream)
        {
            try
            {
                bool deleteOutputFile = false;

                PgpEncryptedDataList      enc;
                PgpObject                 o    = null;
                PgpPrivateKey             sKey = null;
                PgpPublicKeyEncryptedData pbe  = null;

                var pgpF = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream));
                // find secret key
                var pgpSec = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream));

                if (pgpF != null)
                {
                    o = pgpF.NextPgpObject();
                }

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

                // decrypt
                foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
                {
                    sKey = FindSecretKey(pgpSec, pked.KeyId, passPhrase.ToCharArray());

                    if (sKey != null)
                    {
                        pbe = pked;
                        break;
                    }
                }

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

                PgpObjectFactory plainFact = null;

                using (Stream clear = pbe.GetDataStream(sKey))
                {
                    plainFact = new PgpObjectFactory(clear);
                }

                PgpObject message = plainFact.NextPgpObject();

                if (message is PgpCompressedData)
                {
                    PgpCompressedData cData = (PgpCompressedData)message;
                    PgpObjectFactory  of    = null;

                    using (Stream compDataIn = cData.GetDataStream())
                    {
                        of = new PgpObjectFactory(compDataIn);
                    }

                    message = of.NextPgpObject();
                    if (message is PgpOnePassSignatureList)
                    {
                        PgpOnePassSignature ops = ((PgpOnePassSignatureList)message)[0];

                        PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(publicKeyStream));

                        //USE THE BELOW TO CHECK FOR A FAILING SIGNATURE VERIFICATION.
                        //THE CERTIFICATE MATCHING THE KEY ID MUST BE IN THE PUBLIC KEY RING.
                        //long fakeKeyId = 3008998260528343108L;
                        //PgpPublicKey key = pgpRing.GetPublicKey(fakeKeyId);

                        PgpPublicKey key = pgpRing.GetPublicKey(ops.KeyId);

                        ops.InitVerify(key);

                        message = of.NextPgpObject();
                        PgpLiteralData Ld = null;
                        Ld = (PgpLiteralData)message;

                        //THE OUTPUT FILENAME WILL BE BASED ON THE INPUT PARAMETER VALUE TO THIS METHOD. IF YOU WANT TO KEEP THE
                        //ORIGINAL FILENAME, UNCOMMENT THE FOLLOWING LINE.
                        //if (!String.IsNullOrEmpty(Ld.FileName))
                        //    outputFile = Ld.FileName;

                        using (Stream output = File.Create(outputFile))
                        {
                            Stream dIn = Ld.GetInputStream();

                            int ch;
                            while ((ch = dIn.ReadByte()) >= 0)
                            {
                                ops.Update((byte)ch);
                                output.WriteByte((byte)ch);
                            }
                            output.Close();
                        }

                        PgpSignatureList p3       = (PgpSignatureList)of.NextPgpObject();
                        PgpSignature     firstSig = p3[0];
                        if (ops.Verify(firstSig))
                        {
                            Console.Out.WriteLine("signature verified.");
                        }
                        else
                        {
                            Console.Out.WriteLine("signature verification failed.");

                            //YOU MAY OPT TO DELETE THE OUTPUT FILE IN THE EVENT THAT VERIFICATION FAILS.
                            //FILE DELETION HAPPENS FURTHER DOWN IN THIS METHOD
                            //AN ALTERNATIVE IS TO LOG THESE VERIFICATION FAILURE MESSAGES, BUT KEEP THE OUTPUT FILE FOR FURTHER ANALYSIS
                            //deleteOutputFile = true;
                        }
                    }
                    else
                    {
                        PgpLiteralData Ld = null;
                        Ld = (PgpLiteralData)message;
                        using (Stream output = File.Create(outputFile))
                        {
                            Stream unc = Ld.GetInputStream();
                            Streams.PipeAll(unc, output);
                        }
                    }
                }
                else if (message is PgpLiteralData)
                {
                    PgpLiteralData ld          = (PgpLiteralData)message;
                    string         outFileName = ld.FileName;

                    using (Stream fOut = File.Create(outFileName))
                    {
                        Stream unc = ld.GetInputStream();
                        Streams.PipeAll(unc, fOut);
                    }
                }
                else if (message is PgpOnePassSignatureList)
                {
                    throw new PgpException("Encrypted message contains a signed message - not literal data.");
                }
                else
                {
                    throw new PgpException("Message is not a simple encrypted file - type unknown.");
                }

                #region commented code

                if (pbe.IsIntegrityProtected())
                {
                    if (!pbe.Verify())
                    {
                        //msg = "message failed integrity check.";
                        Console.Error.WriteLine("message failed integrity check");

                        //YOU MAY OPT TO DELETE THE OUTPUT FILE IN THE EVENT THAT THE INTEGRITY PROTECTION CHECK FAILS.
                        //FILE DELETION HAPPENS FURTHER DOWN IN THIS METHOD.
                        //AN ALTERNATIVE IS TO LOG THESE VERIFICATION FAILURE MESSAGES, BUT KEEP THE OUTPUT FILE FOR FURTHER ANALYSIS
                        //deleteOutputFile = true;
                    }
                    else
                    {
                        //msg = "message integrity check passed.";
                        Console.Error.WriteLine("message integrity check passed");
                    }
                }
                else
                {
                    //msg = "no message integrity check.";
                    Console.Error.WriteLine("no message integrity check");
                }

                if (deleteOutputFile)
                {
                    File.Delete(outputFile);
                }

                #endregion commented code
            }
            catch (PgpException ex)
            {
                throw;
            }
        }
Ejemplo n.º 27
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);
        }
Ejemplo n.º 28
0
        private void doSigGenerateTest(
            string privateKeyFile,
            string publicKeyFile,
            HashAlgorithmTag digest)
        {
            PgpSecretKeyRing secRing = loadSecretKey(privateKeyFile);
            PgpPublicKeyRing pubRing = loadPublicKey(publicKeyFile);
            string           data    = "hello world!";

            byte[]                dataBytes = Encoding.ASCII.GetBytes(data);
            MemoryStream          bOut      = new MemoryStream();
            MemoryStream          testIn    = new MemoryStream(dataBytes, false);
            PgpSignatureGenerator sGen      = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, digest);

            sGen.InitSign(PgpSignature.BinaryDocument, secRing.GetSecretKey().ExtractPrivateKey("test".ToCharArray()));

            BcpgOutputStream bcOut = new BcpgOutputStream(bOut);

            sGen.GenerateOnePassVersion(false).Encode(bcOut);

            PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();

//			Date testDate = new Date((System.currentTimeMillis() / 1000) * 1000);
            DateTime testDate = new DateTime(
                (DateTime.UtcNow.Ticks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond);

            Stream lOut = lGen.Open(
                new UncloseableStream(bcOut),
                PgpLiteralData.Binary,
                "_CONSOLE",
                dataBytes.Length,
                testDate);

            int ch;

            while ((ch = testIn.ReadByte()) >= 0)
            {
                lOut.WriteByte((byte)ch);
                sGen.Update((byte)ch);
            }

            lGen.Close();

            sGen.Generate().Encode(bcOut);

            PgpObjectFactory        pgpFact = new PgpObjectFactory(bOut.ToArray());
            PgpOnePassSignatureList p1      = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
            PgpOnePassSignature     ops     = p1[0];

            Assert.AreEqual(digest, ops.HashAlgorithm);
            Assert.AreEqual(PublicKeyAlgorithmTag.Dsa, ops.KeyAlgorithm);

            PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject();

            if (!p2.ModificationTime.Equals(testDate))
            {
                Assert.Fail("Modification time not preserved");
            }

            Stream dIn = p2.GetInputStream();

            ops.InitVerify(pubRing.GetPublicKey());

            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
            }

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

            Assert.AreEqual(digest, sig.HashAlgorithm);
            Assert.AreEqual(PublicKeyAlgorithmTag.Dsa, sig.KeyAlgorithm);

            Assert.IsTrue(ops.Verify(sig));
        }
        private SignatureStatus VerifyFileSignature(Stream literalDataStream, PgpOnePassSignatureList pgpOnePassSignatureList, PgpSignatureList pgpSignatureList)
        {
            try
            {
                const int BUFFER_SIZE = 1 << 16; // should always be power of 2

                SignatureStatus signatureStatus = SignatureStatus.Invalid;

                var signatureKeys = GetAllSignatureKeys();

                if (pgpOnePassSignatureList == null)
                {
                    return(SignatureStatus.NoSignature);
                }

                for (int i = 0; i < pgpOnePassSignatureList.Count; i++)
                {
                    if (literalDataStream.CanSeek)
                    {
                        literalDataStream.Seek(0, SeekOrigin.Begin);
                    }

                    PgpOnePassSignature pgpOnePassSignature = pgpOnePassSignatureList[i];
                    Stream dIn   = literalDataStream;
                    var    keyIn = FindSignatureKey(signatureKeys, pgpOnePassSignature.KeyId);
                    if (keyIn == null)
                    {
                        continue;
                    }

                    pgpOnePassSignature.InitVerify(keyIn);

                    byte[] buf = new byte[BUFFER_SIZE];
                    int    len;
                    while ((len = dIn.Read(buf, 0, buf.Length)) > 0)
                    {
                        pgpOnePassSignature.Update(buf, 0, len);
                    }

                    PgpSignature pgpSignature = pgpSignatureList[i];
                    if (pgpOnePassSignature.Verify(pgpSignature))
                    {
                        signatureStatus = SignatureStatus.Valid;
                        break;
                    }
                }

                return(signatureStatus);
            }
            catch
            {
                return(SignatureStatus.Error);
            }
        }
        private SignatureStatus DecryptFile()
        {
            if (InStream.CanSeek)
            {
                InStream.Seek(0, SeekOrigin.Begin);
            }
            var inputStream = PgpUtilities.GetDecoderStream(InStream);

            try
            {
                PgpObjectFactory     pgpF = new PgpObjectFactory(inputStream);
                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();
                }


                var privateKeys = GetAllPrivateKeys();
                //
                // find the secret key
                //
                PgpPrivateKey             sKey = null;
                PgpPublicKeyEncryptedData pbe  = null;

                foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
                {
                    sKey = FindPrivateKey(privateKeys, pked.KeyId);

                    if (sKey != null)
                    {
                        pbe = pked;
                        break;
                    }
                }

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

                Stream clear = pbe.GetDataStream(sKey);

                PgpLiteralData          pgpLiteralData       = null;
                PgpOnePassSignatureList onePassSignatureList = null;
                PgpSignatureList        signatureList        = null;

                PgpObjectFactory pgpObjectFactory = new PgpObjectFactory(clear);
                var pgpObject = pgpObjectFactory.NextPgpObject();
                while (pgpObject != null)
                {
                    if (pgpObject is PgpCompressedData)
                    {
                        var compressedData = (PgpCompressedData)pgpObject;
                        pgpObjectFactory = new PgpObjectFactory(compressedData.GetDataStream());
                        pgpObject        = pgpObjectFactory.NextPgpObject();
                    }

                    if (pgpObject is PgpLiteralData)
                    {
                        pgpLiteralData = pgpObject as PgpLiteralData;
                        //must read directly to continue reading next pgp objects
                        Stream unc = pgpLiteralData.GetInputStream();
                        Streams.PipeAll(unc, OutStream);
                    }
                    else if (pgpObject is PgpOnePassSignatureList)
                    {
                        onePassSignatureList = pgpObject as PgpOnePassSignatureList;
                    }
                    else if (pgpObject is PgpSignatureList)
                    {
                        signatureList = pgpObject as PgpSignatureList;
                    }

                    pgpObject = pgpObjectFactory.NextPgpObject();
                }

                if (pgpLiteralData == null)
                {
                    throw new PgpLitralDataNotFound("couldn't find pgp literal data");
                }



                if (pbe.IsIntegrityProtected())
                {
                    if (!pbe.Verify())
                    {
                        throw new PgpIntegrityCheckFailed("message failed integrity check");
                    }
                }

                if (CheckSignature)
                {
                    if (onePassSignatureList == null || signatureList == null)
                    {
                        return(SignatureStatus.NoSignature);
                    }
                    else
                    {
                        return(VerifyFileSignature(OutStream, onePassSignatureList, signatureList));
                    }
                }
                else
                {
                    return(SignatureStatus.NotChecked);
                }
            }
            catch
            {
                throw;
            }
        }