Close() public method

Close the compressed object.
public Close ( ) : void
return void
        /**
         * Encrypts given {@code message}. Output is written ot the {@code encryptedMessage} output stream.
         * Message is encrypted usign symmetric algorithm, default is {@link SymmetricKeyAlgorithmTags#TRIPLE_DES}.
         *
         * @param encryptedMessage
         * @param message
         * @param armor                  if output should be armored (BASE64 encoding of binary data)
         * @throws java.io.IOException
         * @throws java.security.NoSuchProviderException
         * @throws PgpException
         */
        public void encryptMessage(Stream encryptedMessage, string message, bool armor)
        {
            PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
            PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator();

            // we want to generate compressed data
            MemoryStream byteOut = new MemoryStream();

            writeClearDataToByteOut(compressedDataGenerator, literalDataGenerator, Encoding.ASCII.GetBytes(message), byteOut);

            compressedDataGenerator.Close();

            MemoryStream encryptedOut = new MemoryStream();

            Stream outStream = encryptedOut;
            if (armor) {
                // output will be BASE64 encoded
                outStream = new ArmoredOutputStream(outStream);
            }

            Stream encryptedDataOut = null;
            try {
                byte[] bytes = byteOut.ToArray();
                encryptedDataOut = createEncryptedDataGenerator().Open(outStream, bytes.Length);
                encryptedDataOut.Write(bytes, 0, bytes.Length);  // obtain the actual bytes from the compressed stream
            } finally {
                if (encryptedDataOut != null) {
                    encryptedDataOut.Close();
                }
                outStream.Close();
            }

            var encData = encryptedOut.ToArray();
            encryptedMessage.Write(encData, 0, encData.Length);
        }
        private const int BufferSize = 0x10000; // should always be power of 2 

        #region Encrypt
        
        /// <summary>
        /// Encrypts the file.
        /// </summary>
        /// <param name="inputFile">The input file.</param>
        /// <param name="outputFile">The output file.</param>
        /// <param name="publicKeyFile">The public key file.</param>
        /// <param name="armor">if set to <c>true</c> [armor].</param>
        /// <param name="withIntegrityCheck">if set to <c>true</c> [with integrity check].</param>
        public static void EncryptFile(string inputFile, string outputFile, string publicKeyFile, bool armor, bool withIntegrityCheck)
        {
            try
            {
                using (Stream publicKeyStream = File.OpenRead(publicKeyFile))
                {
                    PgpPublicKey encKey = ReadPublicKey(publicKeyStream);

                    using (MemoryStream bOut = new MemoryStream())
                    {
                        PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
                        PgpUtilities.WriteFileToLiteralData(comData.Open(bOut), PgpLiteralData.Binary, new FileInfo(inputFile));

                        comData.Close();
                        PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());

                        cPk.AddMethod(encKey);
                        byte[] bytes = bOut.ToArray();

                        using (Stream outputStream = File.Create(outputFile))
                        {
                            if (armor)
                            {
                                using (ArmoredOutputStream armoredStream = new ArmoredOutputStream(outputStream))
                                {
                                    using (Stream cOut = cPk.Open(armoredStream, bytes.Length))
                                    {
                                        cOut.Write(bytes, 0, bytes.Length);
                                    }
                                }
                            }
                            else
                            {
                                using (Stream cOut = cPk.Open(outputStream, bytes.Length))
                                {
                                    cOut.Write(bytes, 0, bytes.Length);
                                }
                            }
                        }
                    }
                }
            }
            catch (PgpException e)
            {
                throw e;
            }
        }
        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);

                }
            }
        }
        //public static string GetPrivateKeyXml(string inputData)
        //{
        //    Stream inputStream = StreamHelper.GetStream(inputData);
        //    PgpObjectFactory pgpFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream));
        //    PgpObject pgp = null;
        //    if (pgpFactory != null)
        //    {
        //        pgp = pgpFactory.NextPgpObject();
        //    }

        //    PgpEncryptedDataList encryptedData = null;
        //    if (pgp is PgpEncryptedDataList)
        //    {
        //        encryptedData = (PgpEncryptedDataList)pgp;
        //    }
        //    else
        //    {
        //        encryptedData = (PgpEncryptedDataList)pgpFactory.NextPgpObject();
        //    }

        //    Stream privateKeyStream = File.OpenRead(PrivateKeyOnlyPath);

        //    // find secret key
        //    PgpSecretKeyRingBundle pgpKeyRing = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream));
        //    PgpPrivateKey privateKey = null;

        //    foreach (PgpPublicKeyEncryptedData pked in encryptedData.GetEncryptedDataObjects())
        //    {
        //        privateKey = FindSecretKey(pgpKeyRing, pked.KeyId, Password.ToCharArray());
        //        if (privateKey != null)
        //        {
        //            //pubKeyData = pked;
        //            break;
        //        }
        //    }

        //    // get xml:
        //    RsaPrivateCrtKeyParameters rpckp = ((RsaPrivateCrtKeyParameters)privateKey.Key);
        //    RSAParameters dotNetParams = DotNetUtilities.ToRSAParameters(rpckp);
        //    RSA rsa = RSA.Create();
        //    rsa.ImportParameters(dotNetParams);
        //    string xmlPrivate = rsa.ToXmlString(true);

        //    return xmlPrivate;
        //}

        #endregion

        #region helpers

        /// <summary>
        /// 
        /// </summary>
        /// <param name="clearData"></param>
        /// <param name="fileName">File name reference for compression to include (not fully qualified).</param>
        /// <param name="algorithm"></param>
        /// <returns></returns>
        private static byte[] Compress(byte[] clearData, string fileName, CompressionAlgorithmTag algorithm)
        {
            MemoryStream bOut = new MemoryStream();

            PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(algorithm);
            Stream cos = comData.Open(bOut); // open it with the final destination
            PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator();

            // we want to Generate compressed data. This might be a user option later,
            // in which case we would pass in bOut.
            Stream pOut = lData.Open(
            cos,                    // the compressed output stream
            PgpLiteralData.Binary,
            fileName,               // "filename" to store
            clearData.Length,       // length of clear data
            DateTime.UtcNow         // current time
            );

            pOut.Write(clearData, 0, clearData.Length);
            pOut.Close();

            comData.Close();

            return bOut.ToArray();
        }
        //public static void EncryptPgpFile(string inputFile, string outputFile)
        //{
        //    // use armor: yes, use integrity check? yes?
        //    EncryptPgpFile(inputFile, outputFile, PublicKeyPath, true, true);
        //}

        public static void EncryptPgpFile(string inputFile, string outputFile, string publicKeyFile, bool armor, bool withIntegrityCheck)
        {
            using (Stream publicKeyStream = File.OpenRead(publicKeyFile))
            {
                PgpPublicKey pubKey = ReadPublicKey(publicKeyStream);

                using (MemoryStream outputBytes = new MemoryStream())
                {
                    PgpCompressedDataGenerator dataCompressor = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
                    PgpUtilities.WriteFileToLiteralData(dataCompressor.Open(outputBytes), PgpLiteralData.Binary, new FileInfo(inputFile));

                    dataCompressor.Close();
                    PgpEncryptedDataGenerator dataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());

                    dataGenerator.AddMethod(pubKey);
                    byte[] dataBytes = outputBytes.ToArray();

                    using (Stream outputStream = File.Create(outputFile))
                    {
                        if (armor)
                        {
                            using (ArmoredOutputStream armoredStream = new ArmoredOutputStream(outputStream))
                            {
                                IoHelper.WriteStream(dataGenerator.Open(armoredStream, dataBytes.Length), ref dataBytes);
                            }
                        }
                        else
                        {
                            IoHelper.WriteStream(dataGenerator.Open(outputStream, dataBytes.Length), ref dataBytes);
                        }
                    }
                }
            }
        }
        public static void SignAndEncryptFile(string actualFileName, string embeddedFileName,
             Stream privateKeyStream, string passPhrase, Stream publicKeyStream,
             bool armor, bool withIntegrityCheck, Stream outputStream)
        {
            const int BUFFER_SIZE = 1 << 16; // should always be power of 2

            if (armor)
                outputStream = new ArmoredOutputStream(outputStream);

            PgpPublicKey pubKey = ReadPublicKey(publicKeyStream);

            // Init encrypted data generator
            PgpEncryptedDataGenerator encryptedDataGenerator =
                new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());
            encryptedDataGenerator.AddMethod(pubKey);
            Stream encryptedOut = encryptedDataGenerator.Open(outputStream, new byte[BUFFER_SIZE]);

            // Init compression
            PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
            Stream compressedOut = compressedDataGenerator.Open(encryptedOut);

            // Init signature
            PgpSecretKeyRingBundle pgpSecBundle = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream));

            var pgpSecKey = ReadSecretKey(pgpSecBundle);
            if (pgpSecKey == null)
                throw new ArgumentException(pubKey.KeyId.ToString("X") + " could not be found in specified key ring bundle.", "keyId");

            PgpPrivateKey pgpPrivKey = pgpSecKey.ExtractPrivateKey(passPhrase.ToCharArray());
            PgpSignatureGenerator signatureGenerator = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1);
            signatureGenerator.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);
            var userIds = pgpSecKey.PublicKey.GetUserIds();

            string userId = null;
            foreach (string value in userIds)
            {
                // Just the first one!
                userId = value;
                break;
            }

            if (string.IsNullOrEmpty(userId))
            {
                throw new ArgumentException(string.Format("Can't find userId in signing key. KeyId '{0}'.", pubKey.KeyId.ToString("X")));
            }

            PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();
            spGen.SetSignerUserId(false, userId);
            signatureGenerator.SetHashedSubpackets(spGen.Generate());

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

            // Create the Literal Data generator output stream
            PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator();

            // NOTE: Commented this out because it uses FileInfo to get stats on files and won't work properly

            FileInfo embeddedFile = new FileInfo(embeddedFileName);
            FileInfo actualFile = new FileInfo(actualFileName);

            if (!actualFile.Exists)
            {
                throw new FileNotFoundException(actualFile.FullName);
            }

            // TODO: Use lastwritetime from source file
            Stream literalOut = literalDataGenerator.Open(compressedOut, PgpLiteralData.Binary, embeddedFile.Name, actualFile.LastWriteTime, new byte[BUFFER_SIZE]);

            // Open the input file
            FileStream inputStream = actualFile.OpenRead();

            byte[] buf = new byte[BUFFER_SIZE];
            int len;
            while ((len = inputStream.Read(buf, 0, buf.Length)) > 0)
            {
                literalOut.Write(buf, 0, len);
                signatureGenerator.Update(buf, 0, len);
            }

            literalOut.Close();
            literalDataGenerator.Close();
            signatureGenerator.Generate().Encode(compressedOut);
            compressedOut.Close();
            compressedDataGenerator.Close();
            encryptedOut.Close();
            encryptedDataGenerator.Close();
            inputStream.Close();

            if (armor)
                outputStream.Close();
        }
        /**
         * Generates an encapsulated signed file.
         */
        public void signMessage(Stream unsignedContent, Stream signedContent, bool armor)
        {
            if (armor) {
                // output will be BASE64 encoded
                signedContent = new ArmoredOutputStream(signedContent);
            }

            PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.ZLib);
            PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator();
            try {
                BcpgOutputStream bcpgSignedContentOut = new BcpgOutputStream(compressedDataGenerator.Open(signedContent));

                PgpPrivateKey pgpPrivateKey = secretKeyForSigning.ExtractPrivateKey(secretKeyPassword);
                PgpSignatureGenerator signatureGenerator = createSignatureGenerator(pgpPrivateKey);

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

                Stream literalDataOut = literalDataGenerator.Open(bcpgSignedContentOut, PgpLiteralData.Binary, "_CONSOLE", unsignedContent.Length, DateTime.Now);

                updateSignatureGeneratorWithInputBytes(unsignedContent, signatureGenerator, literalDataOut);
                signatureGenerator.Generate().Encode(bcpgSignedContentOut);
            } finally {
                literalDataGenerator.Close();
                compressedDataGenerator.Close();
                signedContent.Close();
            }
        }