Пример #1
0
		private void doTestCompression(
			CompressionAlgorithmTag	type,
			bool					streamClose)
		{
			MemoryStream bOut = new MemoryStream();
			PgpCompressedDataGenerator cPacket = new PgpCompressedDataGenerator(type);
			Stream os = cPacket.Open(new UncloseableStream(bOut), new byte[Data.Length - 1]);
			os.Write(Data, 0, Data.Length);

			if (streamClose)
			{
				os.Close();
			}
			else
			{
				cPacket.Close();
			}

			ValidateData(bOut.ToArray());

			try
			{
				os.Close();
				cPacket.Close();
			}
			catch (Exception)
			{
				Fail("Redundant Close() should be ignored");
			}
		}
Пример #2
0
		internal static byte[] CompressFile(string fileName, CompressionAlgorithmTag algorithm)
		{
			MemoryStream bOut = new MemoryStream();
			PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(algorithm);
			PgpUtilities.WriteFileToLiteralData(comData.Open(bOut), PgpLiteralData.Binary,
				new FileInfo(fileName));
			comData.Close();
			return bOut.ToArray();
		}
Пример #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="outputStream"></param>
        /// <param name="fileName"></param>
        /// <param name="encKeys"></param>
        /// <param name="armor"></param>
        /// <param name="withIntegrityCheck"></param>
        /// <param name="compressionName"></param>
        /// <param name="symmAlgorithm"></param>
        public static void EncryptFile(
            Stream outputStream,
            string fileName,
            PgpPublicKey[] encKeys,
            bool armor,
            bool withIntegrityCheck,
            string compressionName,
            string symmAlgorithm)
        {
            if (armor)
            {
                var aOutStream = new ArmoredOutputStream(outputStream);
                aOutStream.SetHeader("Version", "Posh-OpenPGP");
                outputStream = aOutStream;
            }

            CompressionAlgorithmTag comptype;

            if (string.Equals(compressionName, "Uncompressed", StringComparison.CurrentCultureIgnoreCase))
            {
                comptype = CompressionAlgorithmTag.Uncompressed;
            }
            else if (string.Equals(compressionName, "Zip", StringComparison.CurrentCultureIgnoreCase))
            {
                comptype = CompressionAlgorithmTag.Zip;
            }
            else if (string.Equals(compressionName, "Zlib", StringComparison.CurrentCultureIgnoreCase))
            {
                comptype = CompressionAlgorithmTag.ZLib;
            }
            else if (string.Equals(compressionName, "BZip2", StringComparison.CurrentCultureIgnoreCase))
            {
                comptype = CompressionAlgorithmTag.BZip2;
            }
            else
            {
                comptype = CompressionAlgorithmTag.Zip;
            }

            SymmetricKeyAlgorithmTag symtype;

            if (string.Equals(symmAlgorithm, "Aes256", StringComparison.CurrentCultureIgnoreCase))
            {
                symtype = SymmetricKeyAlgorithmTag.Aes256;
            }
            else if (string.Equals(symmAlgorithm, "Aes192", StringComparison.CurrentCultureIgnoreCase))
            {
                symtype = SymmetricKeyAlgorithmTag.Aes192;
            }
            else if (string.Equals(symmAlgorithm, "Aes128", StringComparison.CurrentCultureIgnoreCase))
            {
                symtype = SymmetricKeyAlgorithmTag.Aes128;
            }
            else if (string.Equals(symmAlgorithm, "Blowfish", StringComparison.CurrentCultureIgnoreCase))
            {
                symtype = SymmetricKeyAlgorithmTag.Blowfish;
            }
            else if (string.Equals(symmAlgorithm, "Twofish", StringComparison.CurrentCultureIgnoreCase))
            {
                symtype = SymmetricKeyAlgorithmTag.Twofish;
            }
            else if (string.Equals(symmAlgorithm, "Cast5", StringComparison.CurrentCultureIgnoreCase))
            {
                symtype = SymmetricKeyAlgorithmTag.Cast5;
            }
            else if (string.Equals(symmAlgorithm, "Idea", StringComparison.CurrentCultureIgnoreCase))
            {
                symtype = SymmetricKeyAlgorithmTag.Idea;
            }
            else if (string.Equals(symmAlgorithm, "DES", StringComparison.CurrentCultureIgnoreCase))
            {
                symtype = SymmetricKeyAlgorithmTag.Des;
            }
            else if (string.Equals(symmAlgorithm, "3DES", StringComparison.CurrentCultureIgnoreCase))
            {
                symtype = SymmetricKeyAlgorithmTag.TripleDes;
            }
            else
            {
                symtype = SymmetricKeyAlgorithmTag.Twofish;
            }

            var bOut    = new MemoryStream();
            var comData = new PgpCompressedDataGenerator(
                comptype);

            PgpUtilities.WriteFileToLiteralData(
                comData.Open(bOut),
                PgpLiteralData.Binary,
                new FileInfo(fileName));

            comData.Close();

            var cPk = new PgpEncryptedDataGenerator(
                symtype, withIntegrityCheck,
                new SecureRandom());

            foreach (var encKey in encKeys)
            {
                cPk.AddMethod(encKey);
            }
            var bytes = bOut.ToArray();
            var cOut  = cPk.Open(outputStream, bytes.Length);

            cOut.Write(bytes, 0, bytes.Length);
            cOut.Close();
            if (armor)
            {
                outputStream.Close();
            }
        }
Пример #4
0
        /// <summary>
        /// PGP Encrypt the file.
        /// </summary>
        /// <param name="inputFilePath"></param>
        /// <param name="outputFilePath"></param>
        /// <param name="publicKeyFilePath"></param>
        /// <param name="armor"></param>
        /// <param name="withIntegrityCheck"></param>
        public void EncryptFile(string inputFilePath, string outputFilePath, string publicKeyFilePath,
                                bool armor = true, bool withIntegrityCheck = true)
        {
            if (String.IsNullOrEmpty(inputFilePath))
            {
                throw new ArgumentException("InputFilePath");
            }
            if (String.IsNullOrEmpty(outputFilePath))
            {
                throw new ArgumentException("OutputFilePath");
            }
            if (String.IsNullOrEmpty(publicKeyFilePath))
            {
                throw new ArgumentException("PublicKeyFilePath");
            }

            if (!File.Exists(inputFilePath))
            {
                throw new FileNotFoundException(String.Format("Input file [{0}] does not exist.", inputFilePath));
            }
            if (!File.Exists(publicKeyFilePath))
            {
                throw new FileNotFoundException(String.Format("Public Key file [{0}] does not exist.", publicKeyFilePath));
            }

            using (Stream pkStream = File.OpenRead(publicKeyFilePath))
            {
                using (MemoryStream @out = new MemoryStream())
                {
                    if (CompressionAlgorithm != ChoCompressionAlgorithm.Uncompressed)
                    {
                        PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator((CompressionAlgorithmTag)(int)CompressionAlgorithm);
                        PgpUtilities.WriteFileToLiteralData(comData.Open(@out), FileTypeToChar(), new FileInfo(inputFilePath));
                        comData.Close();
                    }
                    else
                    {
                        PgpUtilities.WriteFileToLiteralData(@out, FileTypeToChar(), new FileInfo(inputFilePath));
                    }

                    PgpEncryptedDataGenerator pk = new PgpEncryptedDataGenerator((SymmetricKeyAlgorithmTag)(int)SymmetricKeyAlgorithm, withIntegrityCheck, new SecureRandom());
                    pk.AddMethod(ReadPublicKey(pkStream));

                    byte[] bytes = @out.ToArray();

                    using (Stream outStream = File.Create(outputFilePath))
                    {
                        if (armor)
                        {
                            using (ArmoredOutputStream armoredStream = new ArmoredOutputStream(outStream))
                            {
                                using (Stream armoredOutStream = pk.Open(armoredStream, bytes.Length))
                                {
                                    armoredOutStream.Write(bytes, 0, bytes.Length);
                                }
                            }
                        }
                        else
                        {
                            using (Stream plainStream = pk.Open(outStream, bytes.Length))
                            {
                                plainStream.Write(bytes, 0, bytes.Length);
                            }
                        }
                    }
                }
            }
        }
Пример #5
0
        public override void PerformTest()
        {
            byte[] data = DecryptMessage(enc1);
            if (data[0] != 'h' || data[1] != 'e' || data[2] != 'l')
            {
                Fail("wrong plain text in packet");
            }

            //
            // create a PBE encrypted message and read it back.
            //
            byte[] text = Encoding.ASCII.GetBytes("hello world!\n");

            //
            // encryption step - convert to literal data, compress, encode.
            //
            MemoryStream bOut = new UncloseableMemoryStream();

            PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(
                CompressionAlgorithmTag.Zip);

            PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator();
            Stream comOut = comData.Open(new UncloseableStream(bOut));
            Stream ldOut  = lData.Open(
                new UncloseableStream(comOut),
                PgpLiteralData.Binary,
                PgpLiteralData.Console,
                text.Length,
                TestDateTime);

            ldOut.Write(text, 0, text.Length);
            ldOut.Close();

            comOut.Close();

            //
            // encrypt - with stream close
            //
            MemoryStream cbOut            = new UncloseableMemoryStream();
            PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(
                SymmetricKeyAlgorithmTag.Cast5, new SecureRandom());

            cPk.AddMethod(pass, HashAlgorithmTag.Sha1);

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

            cOut.Write(bOutData, 0, bOutData.Length);
            cOut.Close();

            data = DecryptMessage(cbOut.ToArray());
            if (!Arrays.AreEqual(data, text))
            {
                Fail("wrong plain text in generated packet");
            }

            //
            // encrypt - with generator close
            //
            cbOut = new UncloseableMemoryStream();
            cPk   = new PgpEncryptedDataGenerator(
                SymmetricKeyAlgorithmTag.Cast5, new SecureRandom());

            cPk.AddMethod(pass, HashAlgorithmTag.Sha1);

            bOutData = bOut.ToArray();
            cOut     = cPk.Open(new UncloseableStream(cbOut), bOutData.Length);
            cOut.Write(bOutData, 0, bOutData.Length);

            cPk.Close();

            data = DecryptMessage(cbOut.ToArray());

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

            //
            // encrypt - partial packet style.
            //
            SecureRandom rand = new SecureRandom();

            byte[] test = new byte[1233];

            rand.NextBytes(test);

            bOut = new UncloseableMemoryStream();

            comData = new PgpCompressedDataGenerator(
                CompressionAlgorithmTag.Zip);
            comOut = comData.Open(new UncloseableStream(bOut));

            lData = new PgpLiteralDataGenerator();
            ldOut = lData.Open(
                new UncloseableStream(comOut),
                PgpLiteralData.Binary,
                PgpLiteralData.Console,
                TestDateTime,
                new byte[16]);

            ldOut.Write(test, 0, test.Length);
            lData.Close();

            comData.Close();
            cbOut = new UncloseableMemoryStream();
            cPk   = new PgpEncryptedDataGenerator(
                SymmetricKeyAlgorithmTag.Cast5, rand);

            cPk.AddMethod(pass, HashAlgorithmTag.Sha1);

            cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]);
            {
                byte[] tmp = bOut.ToArray();
                cOut.Write(tmp, 0, tmp.Length);
            }

            cPk.Close();

            data = DecryptMessage(cbOut.ToArray());
            if (!Arrays.AreEqual(data, test))
            {
                Fail("wrong plain text in generated packet");
            }

            //
            // with integrity packet
            //
            cbOut = new UncloseableMemoryStream();
            cPk   = new PgpEncryptedDataGenerator(
                SymmetricKeyAlgorithmTag.Cast5, true, rand);

            cPk.AddMethod(pass, HashAlgorithmTag.Sha1);

            cOut     = cPk.Open(new UncloseableStream(cbOut), new byte[16]);
            bOutData = bOut.ToArray();
            cOut.Write(bOutData, 0, bOutData.Length);
            cPk.Close();

            data = DecryptMessage(cbOut.ToArray());
            if (!Arrays.AreEqual(data, test))
            {
                Fail("wrong plain text in generated packet");
            }

            //
            // decrypt with buffering
            //
            data = DecryptMessageBuffered(cbOut.ToArray());
            if (!AreEqual(data, test))
            {
                Fail("wrong plain text in buffer generated packet");
            }

            //
            // sample message
            //
            PgpObjectFactory pgpFact = new PgpObjectFactory(testPBEAsym);

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

            PgpPbeEncryptedData pbe = (PgpPbeEncryptedData)enc[1];

            Stream clear = pbe.GetDataStream("password".ToCharArray());

            pgpFact = new PgpObjectFactory(clear);

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

            Stream unc = ld.GetInputStream();

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

            if (!AreEqual(bytes, Hex.Decode("5361742031302e30322e30370d0a")))
            {
                Fail("data mismatch on combined PBE");
            }

            //
            // with integrity packet - one byte message
            //
            byte[] msg = new byte[1];
            bOut = new MemoryStream();

            comData = new PgpCompressedDataGenerator(
                CompressionAlgorithmTag.Zip);

            lData  = new PgpLiteralDataGenerator();
            comOut = comData.Open(new UncloseableStream(bOut));
            ldOut  = lData.Open(
                new UncloseableStream(comOut),
                PgpLiteralData.Binary,
                PgpLiteralData.Console,
                msg.Length,
                TestDateTime);

            ldOut.Write(msg, 0, msg.Length);

            ldOut.Close();

            comOut.Close();

            cbOut = new MemoryStream();
            cPk   = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, true, rand);

            cPk.AddMethod(pass, HashAlgorithmTag.Sha1);

            cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]);

            data = bOut.ToArray();
            cOut.Write(data, 0, data.Length);

            cOut.Close();

            data = DecryptMessage(cbOut.ToArray());
            if (!AreEqual(data, msg))
            {
                Fail("wrong plain text in generated packet");
            }

            //
            // decrypt with buffering
            //
            data = DecryptMessageBuffered(cbOut.ToArray());
            if (!AreEqual(data, msg))
            {
                Fail("wrong plain text in buffer generated packet");
            }
        }
Пример #6
0
        /// <summary>
        /// PGP Encrypt the stream.
        /// </summary>
        /// <param name="inputStream"></param>
        /// <param name="outputStream"></param>
        /// <param name="publicKeyFilePaths"></param>
        /// <param name="armor"></param>
        /// <param name="withIntegrityCheck"></param>
        public void EncryptStream(Stream inputStream, Stream outputStream, IEnumerable <Stream> publicKeyStreams, bool armor = true, bool withIntegrityCheck = true)
        {
            //Avoid multiple enumerations of 'publicKeyFilePaths'
            Stream[] publicKeys = publicKeyStreams.ToArray();

            if (inputStream == null)
            {
                throw new ArgumentException("InputStream");
            }
            if (outputStream == null)
            {
                throw new ArgumentException("OutputStream");
            }
            foreach (Stream publicKey in publicKeys)
            {
                if (publicKey == null)
                {
                    throw new ArgumentException("PublicKeyStream");
                }
            }

            using (MemoryStream @out = new MemoryStream())
            {
                if (CompressionAlgorithm != CompressionAlgorithmTag.Uncompressed)
                {
                    PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(CompressionAlgorithm);
                    Utilities.WriteStreamToLiteralData(comData.Open(@out), FileTypeToChar(), inputStream, "name");
                    comData.Close();
                }
                else
                {
                    Utilities.WriteStreamToLiteralData(@out, FileTypeToChar(), inputStream, "name");
                }

                PgpEncryptedDataGenerator pk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithm, withIntegrityCheck, new SecureRandom());

                foreach (Stream publicKey in publicKeys)
                {
                    pk.AddMethod(Utilities.ReadPublicKey(publicKey));
                }

                byte[] bytes = @out.ToArray();

                if (armor)
                {
                    using (ArmoredOutputStream armoredStream = new ArmoredOutputStream(outputStream))
                    {
                        using (Stream armoredOutStream = pk.Open(armoredStream, bytes.Length))
                        {
                            armoredOutStream.Write(bytes, 0, bytes.Length);
                        }
                    }
                }
                else
                {
                    using (Stream plainStream = pk.Open(outputStream, bytes.Length))
                    {
                        plainStream.Write(bytes, 0, bytes.Length);
                    }
                }
            }
        }
Пример #7
0
        /// <summary>
        ///     Signs the specified byte array using the specified key after unlocking the key with the specified passphrase.
        /// </summary>
        /// <param name="bytes">The byte array containing the payload to sign.</param>
        /// <param name="key">The PGP key to be used to sign the payload.</param>
        /// <param name="passphrase">The passphrase used to unlock the PGP key.</param>
        /// <returns>A byte array containing the generated PGP signature.</returns>
        public static byte[] Sign(byte[] bytes, string key, string passphrase)
        {
            // prepare a memory stream to hold the signature
            MemoryStream memoryStream = new MemoryStream();

            // prepare an armored output stream to produce an armored ASCII signature
            Stream outputStream = new ArmoredOutputStream(memoryStream);

            // retrieve the keys
            PgpSecretKey  secretKey  = ReadSecretKeyFromString(key);
            PgpPrivateKey privateKey = secretKey.ExtractPrivateKey(passphrase.ToCharArray());

            // create and initialize a signature generator
            PgpSignatureGenerator signatureGenerator = new PgpSignatureGenerator(secretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha512);

            signatureGenerator.InitSign(PgpSignature.BinaryDocument, privateKey);

            // retrieve the first user id contained within the public key and use it to set the signature signer
            foreach (string userId in secretKey.PublicKey.GetUserIds())
            {
                PgpSignatureSubpacketGenerator signatureSubpacketGenerator = new PgpSignatureSubpacketGenerator();
                signatureSubpacketGenerator.SetSignerUserId(false, userId);
                signatureGenerator.SetHashedSubpackets(signatureSubpacketGenerator.Generate());

                break;
            }

            // prepare a compressed data generator and compressed output stream to compress the data
            PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.ZLib);
            Stream compressedOutputStream = compressedDataGenerator.Open(outputStream);

            // generate the signature taken pretty much verbatim from the bouncycastle example; not sure what all of it does.
            BcpgOutputStream bcpgOutputStream = new BcpgOutputStream(compressedOutputStream);

            signatureGenerator.GenerateOnePassVersion(false).Encode(bcpgOutputStream);

            PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator();
            Stream literalOutputStream = literalDataGenerator.Open(bcpgOutputStream, PgpLiteralData.Binary, "signatureData", DateTime.UtcNow, new byte[4092]);

            foreach (byte b in bytes)
            {
                literalOutputStream.WriteByte(b);
                signatureGenerator.Update(b);
            }

            literalDataGenerator.Close();

            signatureGenerator.Generate().Encode(bcpgOutputStream);

            compressedDataGenerator.Close();

            outputStream.Close();

            // fetch a byte array containing the contents of the memory stream
            byte[] retVal = memoryStream.ToArray();

            // close the memory stream
            memoryStream.Close();

            // return the generated signature
            return(retVal);
        }
Пример #8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="inStream"></param>
        /// <param name="outStream"></param>
        /// <param name="symmAlgorithm"></param>
        /// <param name="passPhrase"></param>
        /// <param name="armor"></param>
        /// <param name="compressionName"></param>
        /// <param name="withIntegrityCheck"></param>
        public static void Encrypt(
            FileStream inStream,
            Stream outStream,
            string symmAlgorithm,
            char[] passPhrase,
            bool armor,
            string compressionName,
            bool withIntegrityCheck)
        {
            if (armor)
            {
                outStream = new ArmoredOutputStream(outStream);
            }

            // Select the specified compression
            CompressionAlgorithmTag comptype;

            if (string.Equals(compressionName, "Uncompressed", StringComparison.CurrentCultureIgnoreCase))
            {
                comptype = CompressionAlgorithmTag.Uncompressed;
            }
            else if (string.Equals(compressionName, "Zip", StringComparison.CurrentCultureIgnoreCase))
            {
                comptype = CompressionAlgorithmTag.Zip;
            }
            else if (string.Equals(compressionName, "Zlib", StringComparison.CurrentCultureIgnoreCase))
            {
                comptype = CompressionAlgorithmTag.ZLib;
            }
            else if (string.Equals(compressionName, "BZip2", StringComparison.CurrentCultureIgnoreCase))
            {
                comptype = CompressionAlgorithmTag.BZip2;
            }
            else
            {
                comptype = CompressionAlgorithmTag.Zip;
            }

            SymmetricKeyAlgorithmTag symtype;

            if (string.Equals(symmAlgorithm, "Aes256", StringComparison.CurrentCultureIgnoreCase))
            {
                symtype = SymmetricKeyAlgorithmTag.Aes256;
            }
            else if (string.Equals(symmAlgorithm, "Aes192", StringComparison.CurrentCultureIgnoreCase))
            {
                symtype = SymmetricKeyAlgorithmTag.Aes192;
            }
            else if (string.Equals(symmAlgorithm, "Aes128", StringComparison.CurrentCultureIgnoreCase))
            {
                symtype = SymmetricKeyAlgorithmTag.Aes128;
            }
            else if (string.Equals(symmAlgorithm, "Blowfish", StringComparison.CurrentCultureIgnoreCase))
            {
                symtype = SymmetricKeyAlgorithmTag.Blowfish;
            }
            else if (string.Equals(symmAlgorithm, "Twofish", StringComparison.CurrentCultureIgnoreCase))
            {
                symtype = SymmetricKeyAlgorithmTag.Twofish;
            }
            else if (string.Equals(symmAlgorithm, "Cast5", StringComparison.CurrentCultureIgnoreCase))
            {
                symtype = SymmetricKeyAlgorithmTag.Cast5;
            }
            else if (string.Equals(symmAlgorithm, "Idea", StringComparison.CurrentCultureIgnoreCase))
            {
                symtype = SymmetricKeyAlgorithmTag.Idea;
            }
            else
            {
                symtype = SymmetricKeyAlgorithmTag.Twofish;
            }

            // Create Encryption Generator
            var encGen = new PgpEncryptedDataGenerator(symtype, withIntegrityCheck, new SecureRandom());

            encGen.AddMethod(passPhrase);

            // Initialize compressor
            var compressedOut = new MemoryStream();
            var comData       = new PgpCompressedDataGenerator(comptype);


            PgpUtilities.WriteFileToLiteralData(comData.Open(compressedOut), PgpLiteralData.Binary,
                                                new FileInfo(inStream.Name));
            comData.Close();

            //Save encrypted data in to the stream.
            var compressData = compressedOut.ToArray();
            var encOut       = encGen.Open(outStream, compressData.Length);

            encOut.Write(compressData, 0, compressData.Length);
            encOut.Close();

            if (armor)
            {
                outStream.Close();
            }
        }
Пример #9
0
		public override void PerformTest()
        {
            byte[] data = DecryptMessage(enc1);
            if (data[0] != 'h' || data[1] != 'e' || data[2] != 'l')
            {
                Fail("wrong plain text in packet");
            }

			//
            // create a PBE encrypted message and read it back.
            //
			byte[] text = Encoding.ASCII.GetBytes("hello world!\n");

			//
            // encryption step - convert to literal data, compress, encode.
            //
            MemoryStream bOut = new UncloseableMemoryStream();

            PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(
                CompressionAlgorithmTag.Zip);

            PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator();
			Stream comOut = comData.Open(new UncloseableStream(bOut));
            Stream ldOut = lData.Open(
				new UncloseableStream(comOut),
                PgpLiteralData.Binary,
                PgpLiteralData.Console,
                text.Length,
                TestDateTime);

			ldOut.Write(text, 0, text.Length);
			ldOut.Close();

			comOut.Close();

			//
            // encrypt - with stream close
            //
            MemoryStream cbOut = new UncloseableMemoryStream();
            PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(
				SymmetricKeyAlgorithmTag.Cast5, new SecureRandom());

            cPk.AddMethod(pass, HashAlgorithmTag.Sha1);

			byte[] bOutData = bOut.ToArray();
			Stream cOut = cPk.Open(new UncloseableStream(cbOut), bOutData.Length);
            cOut.Write(bOutData, 0, bOutData.Length);
            cOut.Close();

			data = DecryptMessage(cbOut.ToArray());
            if (!Arrays.AreEqual(data, text))
            {
                Fail("wrong plain text in generated packet");
            }

			//
			// encrypt - with generator close
			//
			cbOut = new UncloseableMemoryStream();
			cPk = new PgpEncryptedDataGenerator(
				SymmetricKeyAlgorithmTag.Cast5, new SecureRandom());

            cPk.AddMethod(pass, HashAlgorithmTag.Sha1);

			bOutData = bOut.ToArray();
			cOut = cPk.Open(new UncloseableStream(cbOut), bOutData.Length);
			cOut.Write(bOutData, 0, bOutData.Length);

			cPk.Close();

			data = DecryptMessage(cbOut.ToArray());

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

			//
            // encrypt - partial packet style.
            //
            SecureRandom rand = new SecureRandom();
            byte[] test = new byte[1233];

            rand.NextBytes(test);

			bOut = new UncloseableMemoryStream();

			comData = new PgpCompressedDataGenerator(
				CompressionAlgorithmTag.Zip);
			comOut = comData.Open(new UncloseableStream(bOut));

			lData = new PgpLiteralDataGenerator();
            ldOut = lData.Open(
				new UncloseableStream(comOut),
                PgpLiteralData.Binary,
                PgpLiteralData.Console,
                TestDateTime,
                new byte[16]);

            ldOut.Write(test, 0, test.Length);
            lData.Close();

			comData.Close();
            cbOut = new UncloseableMemoryStream();
            cPk = new PgpEncryptedDataGenerator(
				SymmetricKeyAlgorithmTag.Cast5, rand);

            cPk.AddMethod(pass, HashAlgorithmTag.Sha1);

			cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]);
            {
                byte[] tmp = bOut.ToArray();
                cOut.Write(tmp, 0, tmp.Length);
            }

			cPk.Close();

			data = DecryptMessage(cbOut.ToArray());
            if (!Arrays.AreEqual(data, test))
            {
                Fail("wrong plain text in generated packet");
            }

            //
            // with integrity packet
            //
            cbOut = new UncloseableMemoryStream();
            cPk = new PgpEncryptedDataGenerator(
				SymmetricKeyAlgorithmTag.Cast5, true, rand);

            cPk.AddMethod(pass, HashAlgorithmTag.Sha1);

            cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]);
            bOutData = bOut.ToArray();
            cOut.Write(bOutData, 0, bOutData.Length);
            cPk.Close();

			data = DecryptMessage(cbOut.ToArray());
            if (!Arrays.AreEqual(data, test))
            {
                Fail("wrong plain text in generated packet");
            }

			//
			// decrypt with buffering
			//
			data = DecryptMessageBuffered(cbOut.ToArray());
			if (!AreEqual(data, test))
			{
				Fail("wrong plain text in buffer generated packet");
			}

			//
			// sample message
			//
			PgpObjectFactory pgpFact = new PgpObjectFactory(testPBEAsym);

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

			PgpPbeEncryptedData pbe = (PgpPbeEncryptedData) enc[1];

			Stream clear = pbe.GetDataStream("password".ToCharArray());

			pgpFact = new PgpObjectFactory(clear);

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

			Stream unc = ld.GetInputStream();
			byte[] bytes = Streams.ReadAll(unc);

			if (!AreEqual(bytes, Hex.Decode("5361742031302e30322e30370d0a")))
			{
				Fail("data mismatch on combined PBE");
			}

			//
			// with integrity packet - one byte message
			//
			byte[] msg = new byte[1];
			bOut = new MemoryStream();

			comData = new PgpCompressedDataGenerator(
				CompressionAlgorithmTag.Zip);

			lData = new PgpLiteralDataGenerator();
			comOut = comData.Open(new UncloseableStream(bOut));
			ldOut = lData.Open(
				new UncloseableStream(comOut),
				PgpLiteralData.Binary,
				PgpLiteralData.Console,
				msg.Length,
				TestDateTime);

			ldOut.Write(msg, 0, msg.Length);

			ldOut.Close();

			comOut.Close();
        
			cbOut = new MemoryStream();
			cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, true, rand);

            cPk.AddMethod(pass, HashAlgorithmTag.Sha1);

			cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]);

			data = bOut.ToArray();
			cOut.Write(data, 0, data.Length);

			cOut.Close();

			data = DecryptMessage(cbOut.ToArray());
			if (!AreEqual(data, msg))
			{
				Fail("wrong plain text in generated packet");
			}

			//
			// decrypt with buffering
			//
			data = DecryptMessageBuffered(cbOut.ToArray());
			if (!AreEqual(data, msg))
			{
				Fail("wrong plain text in buffer generated packet");
			}
		}
        public override void PerformTest()
        {
            //
            // Read the public key
            //
            PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey);

            var pubKey = pgpPub.GetPublicKey();

            //
            // Read the private key
            //
            PgpSecretKeyRing sKey = new PgpSecretKeyRing(testPrivKey);
            IPgpSecretKey secretKey = sKey.GetSecretKey();
            IPgpPrivateKey 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);

            IAsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();

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

            PgpPublicKey k1 = pgpKp.PublicKey;
            PgpPrivateKey k2 = pgpKp.PrivateKey;
        }
        /**
        * Generated signature test
        *
        * @param sKey
        * @param pgpPrivKey
        * @return test result
        */
        public void GenerateTest(
            PgpSecretKeyRing sKey,
            IPgpPublicKey     pgpPubKey,
            IPgpPrivateKey    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");
            }
        }
Пример #12
0
        private static void EncryptFile(Stream outputStream, string fileName, PgpPublicKey encKey, bool armor, bool withIntegrityCheck)

        {
            if (armor)

            {
                outputStream = new ArmoredOutputStream(outputStream);
            }

            try

            {
                MemoryStream bOut = new MemoryStream();

                PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(

                    CompressionAlgorithmTag.Zip);

                PgpUtilities.WriteFileToLiteralData(

                    comData.Open(bOut),

                    PgpLiteralData.Binary,

                    new FileInfo(fileName));

                comData.Close();

                PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(

                    SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());

                cPk.AddMethod(encKey);

                byte[] bytes = bOut.ToArray();

                Stream cOut = cPk.Open(outputStream, bytes.Length);

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

                cOut.Close();

                if (armor)

                {
                    outputStream.Close();
                }
            }

            catch (PgpException e)

            {
                Console.Error.WriteLine(e);

                Exception underlyingException = e.InnerException;

                if (underlyingException != null)

                {
                    Console.Error.WriteLine(underlyingException.Message);

                    Console.Error.WriteLine(underlyingException.StackTrace);
                }
            }
        }
Пример #13
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;
        }
Пример #14
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");
            }
        }
Пример #15
0
        public override void PerformTest()
        {
            PgpPublicKey pubKey = null;

            //
            // Read the public key
            //
            PgpObjectFactory pgpFact = new PgpObjectFactory(testPubKeyRing);
            PgpPublicKeyRing pgpPub  = (PgpPublicKeyRing)pgpFact.NextPgpObject();

            pubKey = pgpPub.GetPublicKey();

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

            //
            // Read the private key
            //
            PgpSecretKeyRing sKey       = new PgpSecretKeyRing(testPrivKeyRing);
            PgpSecretKey     secretKey  = sKey.GetSecretKey();
            PgpPrivateKey    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;
            AsymmetricKeyParameter 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);
            PgpPublicKey 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
            //
            BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
            BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);

            ElGamalParameters elParams = new ElGamalParameters(p, g);

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

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

            AsymmetricCipherKeyPair 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.");
//					}
                }
            }
        }
Пример #16
0
		public override void PerformTest()
		{
			PgpPublicKey pubKey = null;

			//
			// Read the public key
			//
			PgpObjectFactory pgpFact = new PgpObjectFactory(testPubKeyRing);
			PgpPublicKeyRing pgpPub = (PgpPublicKeyRing)pgpFact.NextPgpObject();

			pubKey = pgpPub.GetPublicKey();

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

			//
			// Read the private key
			//
			PgpSecretKeyRing	sKey = new PgpSecretKeyRing(testPrivKeyRing);
			PgpSecretKey		secretKey = sKey.GetSecretKey();
			PgpPrivateKey		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;
			AsymmetricKeyParameter 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);
			PgpPublicKey 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
			//
			BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
			BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);

			ElGamalParameters elParams = new ElGamalParameters(p, g);

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

			AsymmetricCipherKeyPair 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.");
//					}
                }
            }
		}
        /// <summary>
        /// Encrypt a file as specified by the input file path.
        /// </summary>
        /// <param name="inputFile">
        /// The file to encrypt.
        /// </param>
        /// <param name="outputFile">
        /// The file to write the encrypted content to.
        /// </param>
        /// <param name="publicKeyFile">
        /// The path to the public key file to use for encryption.
        /// </param>
        /// <param name="symmetricKeyAlgorithm">
        /// Encryption algorithm.
        /// </param>
        /// <param name="armor">
        /// Should the encrypted file be written using ASCII armor?
        /// </param>
        /// <param name="withIntegrityCheck">
        /// Should the integrity be verified?
        /// </param>
        /// <param name="compressionAlgorithm">
        /// Compression algorithm to use.
        /// </param>
        public static void EncryptFile(
            string inputFile,
            string outputFile,
            string publicKeyFile,
            SymmetricKeyAlgorithmTag symmetricKeyAlgorithm = SymmetricKeyAlgorithmTag.Aes256,
            bool armor = true,
            bool withIntegrityCheck = true,
            CompressionAlgorithmTag compressionAlgorithm = CompressionAlgorithmTag.Zip)
        {
            try
            {
                using (Stream publicKeyStream = File.OpenRead(publicKeyFile))
                {
                    PgpPublicKey encKey = PgpKeyHelper.ReadPublicKey(publicKeyStream);

                    using (var memoryStream = new MemoryStream())
                    {
                        var compressedDataGenerator = new PgpCompressedDataGenerator(compressionAlgorithm);
                        WriteFileToLiteralData(
                            compressedDataGenerator.Open(memoryStream),
                            PgpLiteralData.Binary,
                            new FileInfo(inputFile));

                        compressedDataGenerator.Close();
                        var encryptedDataGenerator = new PgpEncryptedDataGenerator(
                            symmetricKeyAlgorithm,
                            withIntegrityCheck,
                            new SecureRandom());

                        encryptedDataGenerator.AddMethod(encKey);
                        var bytes = memoryStream.ToArray();

                        using (Stream outputStream = File.Create(outputFile))
                        {
                            if (armor)
                            {
                                using (var armoredStream = new ArmoredOutputStream(outputStream))
                                    using (var encryptedStream = encryptedDataGenerator.Open(armoredStream, bytes.Length))
                                    {
                                        encryptedStream.Write(bytes, 0, bytes.Length);
                                    }
                            }
                            else
                            {
                                using (
                                    Stream encryptedOutputStream = encryptedDataGenerator.Open(
                                        outputStream,
                                        bytes.Length))
                                {
                                    encryptedOutputStream.Write(bytes, 0, bytes.Length);
                                }
                            }
                        }
                    }
                }
            }
            catch (PgpException exception)
            {
                PgpCommon.DumpException(exception);
                throw;
            }
        }