Exemplo n.º 1
0
        /// <summary>
        /// Attempt to decrypt a PGP protected message using the matching private key.
        /// </summary>
        /// <param name="messageStream">Stream containing the message to decrypt.</param>
        /// <param name="decryptedMessageStream">Stream to write the decrypted message into.</param>
        /// <param name="recipientPrivateKey">The BouncyCastle private key to be used for decryption.</param>
        /// <remarks>The message should be passed in without ASCII Armor.</remarks>
        /// <returns>Whether the decryption completed successfully.</returns>
        public static bool Decrypt(Stream messageStream, Stream decryptedMessageStream, PgpPrivateKey recipientPrivateKey)
        {
            // Decode from Base-64.
            using (Stream decoderStream = PgpUtilities.GetDecoderStream(messageStream))
            {
                // Extract the encrypted data list.
                PgpObjectFactory pgpObjectFactory = new PgpObjectFactory(decoderStream);
                PgpObject        pgpObject        = pgpObjectFactory.NextPgpObject();
                while (!(pgpObject is PgpEncryptedDataList))
                {
                    pgpObject = pgpObjectFactory.NextPgpObject();
                    if (pgpObject == null)
                    {
                        return(false);
                    }
                }
                PgpEncryptedDataList pgpEncryptedDataList = pgpObject as PgpEncryptedDataList;

                // Attempt to extract the encrypted data stream.
                Stream decryptedStream = null;
                foreach (PgpPublicKeyEncryptedData pgpEncryptedData in pgpEncryptedDataList.GetEncryptedDataObjects().Cast <PgpPublicKeyEncryptedData>())
                {
                    if (pgpEncryptedData.KeyId == recipientPrivateKey.KeyId)
                    {
                        decryptedStream = pgpEncryptedData.GetDataStream(recipientPrivateKey);
                    }
                }

                // If we're unable to decrypt any of the streams, fail.
                if (decryptedStream == null)
                {
                    return(false);
                }

                PgpObjectFactory clearPgpObjectFactory = new PgpObjectFactory(decryptedStream);
                PgpObject        message = clearPgpObjectFactory.NextPgpObject();

                // Deal with compression.
                if (message is PgpCompressedData)
                {
                    PgpCompressedData compressedMessage = (PgpCompressedData)message;
                    using (Stream compressedDataStream = compressedMessage.GetDataStream())
                    {
                        PgpObjectFactory compressedPgpObjectFactory = new PgpObjectFactory(compressedDataStream);

                        pgpObject = compressedPgpObjectFactory.NextPgpObject();
                        while (!(pgpObject is PgpLiteralData))
                        {
                            pgpObject = compressedPgpObjectFactory.NextPgpObject();
                            if (pgpObject == null)
                            {
                                return(false);
                            }
                        }
                    }
                }
                else if (message is PgpLiteralData)
                {
                    pgpObject = message;
                }
                else
                {
                    // If not compressed and the following object isn't literal data, fail.
                    decryptedStream.Dispose();
                    return(false);
                }

                // If a literal data stream was found, extract the decrypted message.
                PgpLiteralData literalData = pgpObject as PgpLiteralData;
                if (literalData != null)
                {
                    using (Stream literalDataStream = literalData.GetDataStream())
                    {
                        literalDataStream.CopyTo(decryptedMessageStream);
                    }

                    decryptedStream.Dispose();
                    return(true);
                }
            }

            return(false);
        }
        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.");
//					}
                }
            }
        }
Exemplo n.º 3
0
        private void CheckLiteralData(
            PgpLiteralData	ld,
            byte[]			data)
        {
            if (!ld.FileName.Equals(PgpLiteralData.Console))
                throw new Exception("wrong filename in packet");

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

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