Пример #1
0
        /// <summary>
        /// ## Encrypt
        ///
        /// Encrypts the specified file using the public key provided.
        /// </summary>
        /// <param name="file"></param>
        /// <param name="outputFilePath"></param>
        /// <param name="publicKeyPath"></param>
        public VirtualFileInfo Encrypt(VirtualFileInfo file, string outputFilePath, string publicKeyPath)
        {
            // load public key and encrypt the file
            PgpEncryptedDataGenerator encryption = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, true, new SecureRandom());
            PgpPublicKey publicKey = LoadPublicKey(publicKeyPath);

            encryption.AddMethod(publicKey);

            using (Stream fsOut = File.Create(outputFilePath))
            {
                using (MemoryStream bOut = new MemoryStream())
                {
                    PgpUtilities.WriteFileToLiteralData(bOut, PgpLiteralData.Binary, new FileInfo(file.FullName));
                    byte[] data = bOut.ToArray();

                    using (Stream encryptOut = encryption.Open(fsOut, data.Length))
                    {
                        encryptOut.Write(data, 0, data.Length);
                        encryptOut.Close();
                    }

                    bOut.Close();
                }
                fsOut.Close();
            }

            encryption.Close();
            return(new VirtualFileInfo(outputFilePath));
        }
Пример #2
0
        public static byte[] EncryptPgp(byte[] input, byte[] publicKey)
        {
            using (MemoryStream publicKeyStream = new MemoryStream(publicKey))
                using (MemoryStream outputStream = new MemoryStream())
                    using (MemoryStream encryptedBytes = new MemoryStream())
                    {
                        using (Stream s = new PgpLiteralDataGenerator().Open(outputStream, PgpLiteralData.Binary, PgpLiteralDataGenerator.Console, input.Length, DateTime.Now))
                            using (Stream inputStream = new MemoryStream(input))
                            {
                                s.Write(input, 0, input.Length);
                            }

                        PgpPublicKey pubKey = ReadPublicKey(publicKeyStream);

                        PgpEncryptedDataGenerator dataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, true, new SecureRandom());

                        dataGenerator.AddMethod(pubKey);

                        byte[] output = outputStream.ToArray();

                        using (Stream dgenStream = dataGenerator.Open(encryptedBytes, output.Length)) {
                            dgenStream.Write(output, 0, output.Length);
                        }

                        dataGenerator.Close();

                        return(encryptedBytes.ToArray());
                    }
        }
 public void EncryptAndSign(byte[] data, Stream outStream)
 {
     try
     {
         outStream = new ArmoredOutputStream(outStream);
         PgpEncryptedDataGenerator encryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, new SecureRandom());
         encryptedDataGenerator.AddMethod(publicKey);
         PgpCompressedDataGenerator compressedData = null;
         try
         {
             Stream encryptedOut = encryptedDataGenerator.Open(outStream, new byte[BUFFER_SIZE]);
             compressedData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
             try
             {
                 Stream compressedOut = compressedData.Open(encryptedOut);
                 PgpSignatureGenerator signatureGenerator = createSignatureGenerator();
                 signatureGenerator.GenerateOnePassVersion(false).Encode(compressedOut);
                 WriteToLiteralData(signatureGenerator, compressedOut, data);
                 signatureGenerator.Generate().Encode(compressedOut);
                 compressedOut.Close();
             }
             catch (Exception e)
             {
             }
             encryptedOut.Close();
         }
         finally
         {
             if (compressedData != null)
             {
                 compressedData.Close();
             }
             try
             {
                 encryptedDataGenerator.Close();
             }
             catch (IOException e)
             {
             }
             outStream.Close();
         }
     }
     catch (Exception ex)
     {
         throw new CryptoException(ex.Message, ex);
     }
 }
Пример #4
0
        public static bool Encrypt(string inputfile, Stream outputFile, Stream publickeypath, bool armor, bool withIntegrityCheck)
        {
            bool success = false;

            try
            {
                PgpPublicKey pubKey      = ReadPublicKey(publickeypath);
                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();


                if (armor)
                {
                    using (ArmoredOutputStream armoredStream = new ArmoredOutputStream(outputFile))
                    {
                        IOHelper.WriteStream(dataGenerator.Open(armoredStream, dataBytes.Length), ref dataBytes);
                    }
                }
                else
                {
                    IOHelper.WriteStream(dataGenerator.Open(outputFile, dataBytes.Length), ref dataBytes);
                }
                dataGenerator.Close();
                success = true;
            }
            catch (Exception ex)
            {
                LastException = ex.Message;
            }

            return(success);
        }
Пример #5
0
        public void SignAndEncryptFile(string strActualFileName, string strEmbeddedFileName,
                                       System.IO.Stream strmKeyIn, long lngKeyId, System.IO.Stream strmOutputStream,
                                       char[] szPassword, bool bArmor, bool bWithIntegrityCheck, PgpPublicKey PGP_PublicKey)
        {
            const int iBUFFER_SIZE = 1 << 16; // should always be power of 2

            if (bArmor)
            {
                strmOutputStream = new ArmoredOutputStream(strmOutputStream);
            }

            // Init encrypted data generator
            PgpEncryptedDataGenerator PGP_EncryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, bWithIntegrityCheck, new SecureRandom());

            PGP_EncryptedDataGenerator.AddMethod(PGP_PublicKey);
            System.IO.Stream strmEncryptedOut = PGP_EncryptedDataGenerator.Open(strmOutputStream, new byte[iBUFFER_SIZE]);

            // Init compression
            PgpCompressedDataGenerator PGP_CompressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);

            System.IO.Stream strmCompressedOut = PGP_CompressedDataGenerator.Open(strmEncryptedOut);

            // Init signature
            PgpSecretKeyRingBundle PGP_SecretKeyBundle = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(strmKeyIn));
            PgpSecretKey           PGP_SecretKey       = PGP_SecretKeyBundle.GetSecretKey(lngKeyId);

            if (PGP_SecretKey == null)
            {
                throw new System.ArgumentException(lngKeyId.ToString("X") + " could not be found in specified key ring bundle.", "keyId");
            }

            PgpPrivateKey         PGP_PrivateKey         = PGP_SecretKey.ExtractPrivateKey(szPassword);
            PgpSignatureGenerator PGP_SignatureGenerator = new PgpSignatureGenerator(PGP_SecretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1);

            PGP_SignatureGenerator.InitSign(PgpSignature.BinaryDocument, PGP_PrivateKey);

            foreach (string strUserId in PGP_SecretKey.PublicKey.GetUserIds())
            {
                PgpSignatureSubpacketGenerator PGP_SignatureSubpacketGenerator = new PgpSignatureSubpacketGenerator();
                PGP_SignatureSubpacketGenerator.SetSignerUserId(false, strUserId);
                PGP_SignatureGenerator.SetHashedSubpackets(PGP_SignatureSubpacketGenerator.Generate());
                // Just the first one!
                break;
            }
            PGP_SignatureGenerator.GenerateOnePassVersion(false).Encode(strmCompressedOut);

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

            System.IO.FileInfo fiEmbeddedFile = new System.IO.FileInfo(strEmbeddedFileName);
            System.IO.FileInfo fiActualFile   = new System.IO.FileInfo(strActualFileName);
            // TODO: Use lastwritetime from source file
            System.IO.Stream strmLiteralOut = PGP_LiteralDataGenerator.Open(strmCompressedOut, PgpLiteralData.Binary,
                                                                            fiEmbeddedFile.Name, fiActualFile.LastWriteTime, new byte[iBUFFER_SIZE]);

            // Open the input file
            System.IO.FileStream strmInputStream = fiActualFile.OpenRead();

            byte[] baBuffer = new byte[iBUFFER_SIZE];
            int    iReadLength;

            while ((iReadLength = strmInputStream.Read(baBuffer, 0, baBuffer.Length)) > 0)
            {
                strmLiteralOut.Write(baBuffer, 0, iReadLength);
                PGP_SignatureGenerator.Update(baBuffer, 0, iReadLength);
            }

            strmLiteralOut.Close();
            PGP_LiteralDataGenerator.Close();
            PGP_SignatureGenerator.Generate().Encode(strmCompressedOut);
            strmCompressedOut.Close();
            PGP_CompressedDataGenerator.Close();
            strmEncryptedOut.Close();
            PGP_EncryptedDataGenerator.Close();
            strmInputStream.Close();

            if (bArmor)
            {
                strmOutputStream.Close();
            }
        }
        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");
            }
        }
Пример #7
0
        void SignAndEncryptFile()
        {
            const int BUFFER_SIZE = 1 << 16; // should always be power of 2

            var OutStream = OutFile.OpenWrite();

            PgpEncryptedDataGenerator encryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, WithIntegrityCheck, new SecureRandom());

            foreach (var publicKey in PublicKeys)
            {
                var encKey = ReadPublicKey(publicKey);
                encryptedDataGenerator.AddMethod(encKey);
            }

            Stream outputStream = OutStream;

            if (Armor)
            {
                outputStream = new ArmoredOutputStream(outputStream);
            }

            Stream encryptedOut = encryptedDataGenerator.Open(outputStream, new byte[BUFFER_SIZE]);

            if (Compress)
            {
                // Init compression
                PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
                encryptedOut = compressedDataGenerator.Open(encryptedOut);
            }

            //signing
            List <PgpSignatureGenerator> pgpSignatureGenerators = new List <PgpSignatureGenerator>();

            foreach (var privateKeyInfo in PrivateKeys)
            {
                PgpSecretKey  pgpSecKey  = ReadSecretKey(privateKeyInfo.PrivateKeyStream);
                PgpPrivateKey pgpPrivKey = pgpSecKey.ExtractPrivateKey(privateKeyInfo.PrivateKeyPassword == null ? null : privateKeyInfo.PrivateKeyPassword.ToCharArray());

                PgpSignatureGenerator signatureGenerator = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1);
                signatureGenerator.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

                foreach (string userId in pgpSecKey.PublicKey.GetUserIds())
                {
                    PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();
                    spGen.SetSignerUserId(false, userId);
                    signatureGenerator.SetHashedSubpackets(spGen.Generate());
                    // Just the first one!
                    break;
                }

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

                pgpSignatureGenerators.Add(signatureGenerator);
            }
            // Create the Literal Data generator output stream
            PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator();
            Stream literalOut = literalDataGenerator.Open(encryptedOut, PgpLiteralData.Binary, InFile.Name, InFile.LastWriteTime, new byte[BUFFER_SIZE]);

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

            byte[] buf = new byte[BUFFER_SIZE];
            int    len;

            while ((len = inputStream.Read(buf, 0, buf.Length)) > 0)
            {
                literalOut.Write(buf, 0, len);
                foreach (var signatureGenerator in pgpSignatureGenerators)
                {
                    signatureGenerator.Update(buf, 0, len);
                }
            }

            literalOut.Close();
            literalDataGenerator.Close();
            foreach (var signatureGenerator in pgpSignatureGenerators)
            {
                signatureGenerator.Generate().Encode(encryptedOut);
            }
            encryptedOut.Close();
            encryptedOut.Close();
            encryptedDataGenerator.Close();
            inputStream.Close();


            if (Armor)
            {
                outputStream.Close();
            }

            OutStream.Close();
        }
Пример #8
0
        private byte[] GetEncryptedData(byte[] data)
        {
            var baos   = new MemoryStream();
            var outStr = new ArmoredOutputStream(baos);

            PgpPublicKey publicKey   = null;
            var          inputStream = PgpUtilities.GetDecoderStream(new MemoryStream(_encryptionKey));
            var          pgpPub      = new PgpPublicKeyRingBundle(inputStream);

            for (var i = pgpPub.GetKeyRings().GetEnumerator(); i.MoveNext();)
            {
                var pgpPublicKeyRing = (PgpPublicKeyRing)i.Current;
                if (pgpPublicKeyRing != null)
                {
                    for (var j = pgpPublicKeyRing.GetPublicKeys().GetEnumerator();
                         publicKey == null && j.MoveNext();)
                    {
                        var k = (PgpPublicKey)j.Current;
                        if (k != null && k.IsEncryptionKey)
                        {
                            publicKey = k;
                        }
                    }
                }
            }
            if (publicKey == null)
            {
                throw new Exception("Can't find encryption key in key ring.");
            }

            var           pgpSec     = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(new MemoryStream(_signingKey)));
            PgpPrivateKey privateKey = null;
            PgpSecretKey  secretKey  = null;

            for (var i = pgpSec.GetKeyRings().GetEnumerator(); privateKey == null && i.MoveNext();)
            {
                var keyRing = (PgpSecretKeyRing)i.Current;
                if (keyRing != null)
                {
                    for (var j = keyRing.GetSecretKeys().GetEnumerator(); j.MoveNext();)
                    {
                        secretKey = (PgpSecretKey)j.Current;
                        if (secretKey != null)
                        {
                            privateKey = secretKey.ExtractPrivateKey(_password);
                        }
                        break;
                    }
                }
            }
            if (secretKey == null)
            {
                throw new Exception("Can't find signature key in key ring.");
            }
            var cb = new MemoryStream();
            var compressedGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
            var compressedOut       = compressedGenerator.Open(cb);
            var signatureGenerator  = new PgpSignatureGenerator(secretKey.PublicKey.Algorithm,
                                                                HashAlgorithmTag.Sha512);

            signatureGenerator.InitSign(PgpSignature.BinaryDocument, privateKey);
            for (var i = secretKey.PublicKey.GetUserIds().GetEnumerator(); i.MoveNext();)
            {
                var spGen = new PgpSignatureSubpacketGenerator();
                spGen.SetSignerUserId(false, (String)i.Current);
                signatureGenerator.SetHashedSubpackets(spGen.Generate());
            }
            signatureGenerator.GenerateOnePassVersion(true).Encode(compressedOut);
            var lgen     = new PgpLiteralDataGenerator();
            var finalOut = lgen.Open(compressedOut, PgpLiteralData.Binary, "", DateTime.Now, new byte[4096]);

            finalOut.Write(data, 0, data.Length);
            signatureGenerator.Update(data);
            finalOut.Close();
            lgen.Close();
            signatureGenerator.Generate().Encode(compressedOut);
            compressedGenerator.Close();
            compressedOut.Close();
            var compressedData         = cb.ToArray();
            var encryptedDataGenerator =
                new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, true,
                                              new SecureRandom());

            encryptedDataGenerator.AddMethod(publicKey);
            var encryptedOut = encryptedDataGenerator.Open(outStr, compressedData.Length);

            encryptedOut.Write(compressedData, 0, compressedData.Length);
            encryptedOut.Close();
            encryptedDataGenerator.Close();
            outStr.Close();
            return(baos.ToArray());
        }
Пример #9
0
        // Based on http://jopinblog.wordpress.com/2008/06/23/pgp-single-pass-sign-and-encrypt-with-bouncy-castle/
        /// <summary>
        ///
        /// </summary>
        /// <param name="actualFileName"></param>
        /// <param name="embeddedFileName"></param>
        /// <param name="pgpSecKey"></param>
        /// <param name="outputFileName"></param>
        /// <param name="password"></param>
        /// <param name="armor"></param>
        /// <param name="withIntegrityCheck"></param>
        /// <param name="encKeys"></param>
        /// <param name="compressionName"></param>
        /// <param name="digestName"></param>
        public static void SignAndEncryptFile(string actualFileName,
                                              string embeddedFileName,
                                              PgpSecretKey pgpSecKey,
                                              string outputFileName,
                                              char[] password,
                                              bool armor,
                                              bool withIntegrityCheck,
                                              PgpPublicKey[] encKeys,
                                              string compressionName,
                                              string digestName)
        {
            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;
            }

            HashAlgorithmTag digest;

            if (string.Equals(digestName, "Sha256", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.Sha256;
            }
            else if (string.Equals(digestName, "Sha384", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.Sha384;
            }
            else if (string.Equals(digestName, "Sha512", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.Sha512;
            }
            else if (string.Equals(digestName, "MD5", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.MD5;
            }
            else if (string.Equals(digestName, "RipeMD160", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.RipeMD160;
            }
            else
            {
                digest = HashAlgorithmTag.Sha512;
            }
            const int bufferSize   = 1 << 16; // should always be power of 2
            Stream    outputStream = File.Open(outputFileName, FileMode.Create);

            if (armor)
            {
                var aOutStream = new ArmoredOutputStream(outputStream);
                aOutStream.SetHeader("Version", "Posh-OpenPGP");
                outputStream = aOutStream;
            }

            // Init encrypted data generator
            var encryptedDataGenerator =
                new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());

            // add keys to encrypt to
            foreach (var encKey in encKeys)
            {
                encryptedDataGenerator.AddMethod(encKey);
            }
            var encryptedOut = encryptedDataGenerator.Open(outputStream, new byte[bufferSize]);

            // Init compression
            var compressedDataGenerator = new PgpCompressedDataGenerator(comptype);
            var compressedOut           = compressedDataGenerator.Open(encryptedOut);

            // Init signature
            PgpPrivateKey pgpPrivKey;

            try
            {
                pgpPrivKey = pgpSecKey.ExtractPrivateKey(password);
            }
            catch
            {
                throw new PgpException("Wrong Passphrase, could not extract private key.");
            }
            var signatureGenerator = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, digest);

            signatureGenerator.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

            foreach (string userId in pgpSecKey.PublicKey.GetUserIds())
            {
                var spGen = new PgpSignatureSubpacketGenerator();
                spGen.SetSignerUserId(false, userId);
                signatureGenerator.SetHashedSubpackets(spGen.Generate());

                // Just the first one!
                break;
            }
            signatureGenerator.GenerateOnePassVersion(false).Encode(compressedOut);

            // Create the Literal Data generator output stream
            var literalDataGenerator = new PgpLiteralDataGenerator();
            var embeddedFile         = new FileInfo(embeddedFileName);
            var actualFile           = new FileInfo(actualFileName);

            var literalOut = literalDataGenerator.Open(compressedOut, PgpLiteralData.Binary,
                                                       embeddedFile.Name, DateTime.UtcNow, new byte[bufferSize]);

            // Open the input file
            var inputStream = actualFile.OpenRead();
            var buf         = new byte[bufferSize];
            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();
            }
        }
Пример #10
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");
			}
		}