Пример #1
0
        /// <summary>
        /// PGP-encrypt all data from source stream into destination stream in raw/binary format
        /// </summary>
        /// <param name="publickeysource">Input stream containing public keyring bundle</param>
        /// <param name="publickeyuserid">UserID of key to be used within keyring bundle (if null/empty, first available key in ring will be used)</param>
        /// <param name="clearinput">Input stream containing source data to be encrypted</param>
        /// <param name="encryptedoutput">Output stream to receive raw encrypted data</param>
        /// <remarks>
        /// - Source data will be read asynchronously
        /// - Destination data will be written asynchronously
        /// </remarks>
        public static async Task EncryptRaw(Stream publickeysource, string publickeyuserid, Stream clearinput, Stream encryptedoutput)
        {
            // Create encrypted data generator, using public key extracted from provided source:
            var pgpEncDataGen = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, true, new SecureRandom());

            pgpEncDataGen.AddMethod(await ExtractPublicKey(publickeysource, publickeyuserid));

            // Wrap destination stream in encrypted data generator stream:
            using (var encrypt = pgpEncDataGen.Open(encryptedoutput, new byte[1024]))
            {
                // Wrap encrypted data generator stream in compressed data generator stream:
                var comData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
                using (var compress = comData.Open(encrypt))
                {
                    // Wrap compressed data generator stream in literal data generator stream:
                    var lData = new PgpLiteralDataGenerator();
                    using (var literal = lData.Open(compress, PgpLiteralData.Binary, string.Empty, DateTime.UtcNow, new byte[1024]))
                    {
                        // Stream source data into literal generator (whose output will feed into compression stream,
                        // whose output will feed into encryption stream, whose output will feed into destination):
                        await clearinput.CopyToAsync(literal);
                    }
                }
            }
        }
Пример #2
0
    /**
     * Encrypt the data.
     *
     * @param inputData - byte array to encrypt
     * @param passPhrase - the password returned by "ReadPublicKey"
     * @param withIntegrityCheck - check the data for errors
     * @param armor - protect the data streams
     * @return - encrypted byte array
     */
    public static byte[] Encrypt(byte[] inputData, PgpPublicKey passPhrase, bool withIntegrityCheck, bool armor)
    {
        byte[] processedData = Compress(inputData, PgpLiteralData.Console, CompressionAlgorithmTag.Uncompressed);

        MemoryStream bOut   = new MemoryStream();
        Stream       output = bOut;

        if (armor)
        {
            output = new ArmoredOutputStream(output);
        }

        PgpEncryptedDataGenerator encGen = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());

        encGen.AddMethod(passPhrase);

        Stream encOut = encGen.Open(output, processedData.Length);

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

        if (armor)
        {
            output.Close();
        }

        return(bOut.ToArray());
    }
        private string EncryptPgpStringData(string inputFile, string publicKeyData, bool armor, bool withIntegrityCheck)
        {
            using (Stream publicKeyStream = IoHelper.GetStream(publicKeyData))
            {
                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(TempEncryptedPath))
                    {
                        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);
                        }
                    }
                    return(File.ReadAllText(TempEncryptedPath));
                }
            }
        }
Пример #4
0
        /// <summary>
        /// Build PGP-encrypting (raw/binary format) stream around the provided output stream
        /// </summary>
        /// <param name="publickeysource">Input stream containing public keyring bundle</param>
        /// <param name="publickeyuserid">UserID of key to be used within keyring bundle (if null/empty, first available key in ring will be used)</param>
        /// <param name="encryptedoutput">Output stream to receive raw/binary encrypted data</param>
        /// <returns>
        /// A StreamStack object, into which cleartext data can be written (resulting in encrypted data being written to encryptedoutput)
        /// </returns>
        /// <remarks>
        /// - Caller is responsible for disposing of returned StreamStack (BEFORE disposing of original encryptedoutput Stream)
        /// - Caller is also still responsible for disposing of encryptedinput stream (AFTER disposing of returned StreamStack)
        /// </remarks>
        public static async Task <StreamStack> GetEncryptionStreamRaw(Stream publickeysource, string publickeyuserid, Stream encryptedoutput)
        {
            var encryptionstream = new StreamStack();

            try
            {
                // Create encrypted data generator using public key extracted from provided source:
                var pgpEncDataGen = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, true, new SecureRandom());
                pgpEncDataGen.AddMethod(await ExtractPublicKey(publickeysource, publickeyuserid));

                // Create encrypted data generator stream around destination stream and push on to return value stack:
                encryptionstream.PushStream(pgpEncDataGen.Open(encryptedoutput, new byte[1024]));

                // Create compressed data generator stream around encryption stream and push on to return value stack:
                var comData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
                encryptionstream.PushStream(comData.Open(encryptionstream.GetStream()));

                // Create literal data generator stream around compression stream and push on to return value stack:
                var lData = new PgpLiteralDataGenerator();
                encryptionstream.PushStream(lData.Open(encryptionstream.GetStream(), PgpLiteralData.Binary, string.Empty, DateTime.UtcNow, new byte[1024]));

                // Return stream object (data written to stream at top of stack will be literalized -> compressed -> encrypted):
                return(encryptionstream);
            }
            catch
            {
                encryptionstream.Dispose();
                throw;
            }
        }
Пример #5
0
        private static Stream ChainEncryptedOut(Stream outputStream)
        {
            PgpEncryptedDataGenerator encryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.TripleDes, new SecureRandom());

            encryptedDataGenerator.AddMethod(_encryptionKeys.PublicKey);
            return(encryptedDataGenerator.Open(outputStream, new byte[BUFFER_SIZE]));
        }
Пример #6
0
        public string EncryptMessage(string unencryptedMessage, char[] passPhrase)
        {
            // Convert the input to a byte array. We expect the string to be UTF-8 encoded
            var unencryptedByteArray = Encoding.UTF8.GetBytes(unencryptedMessage);

            var lData = new PgpLiteralDataGenerator();

            // Write the data to a literal
            MemoryStream bOut;

            using (bOut = new MemoryStream())
            {
                using var pOut = lData.Open(bOut, PgpLiteralData.Binary, PgpLiteralData.Console, unencryptedByteArray.Length, DateTime.Now);
                pOut.Write(unencryptedByteArray, 0, unencryptedByteArray.Length);
            }
            lData.Close();

            var cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, true);

            cPk.AddMethod(passPhrase, HashAlgorithmTag.Sha1);

            var bytes = bOut.ToArray();

            MemoryStream encOut;

            using (encOut = new MemoryStream())
            {
                using var cOut = cPk.Open(encOut, bytes.Length);
                cOut.Write(bytes, 0, bytes.Length);
            }

            return(Convert.ToBase64String(encOut.ToArray()));
        }
Пример #7
0
    private void TestFile(string fileName, Encoding encoding, bool bom)
    {
      PGPKeyStorage pGPKeyStorage = ApplicationSetting.ToolSetting.PGPInformation;
      var line1 = $"1\tTest\t{fileName}";
      var line2 = $"2\tTest\t{fileName}";
      var line3 = $"3\tTest\t{fileName}";

      FileSystemUtils.FileDelete(fileName);

      var encryptionKey = pGPKeyStorage.GetEncryptionKey("*****@*****.**");

      using (var encryptor = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.TripleDes, false, new SecureRandom()))
      {
        encryptor.AddMethod(encryptionKey);
        using (encryptedStream = encryptor.Open(new FileStream(fileName, FileMode.Create), new byte[16384]))
        { }

        var compressedStream = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip).Open(encryptedStream);
        using (var stream = new PgpLiteralDataGenerator().Open(compressedStream, PgpLiteralDataGenerator.Utf8, "PGPStream", DateTime.Now, new byte[4096]))
        {
          if (bom)
            stream.WriteByteOrderMark(encoding);
          using (var writer2 = new StreamWriter(stream))
          {
            writer2.WriteLine(line1);
            writer2.WriteLine(line2);
            writer2.WriteLine(line3);
            writer2.Flush();
          }
        }
      }
    }
Пример #8
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));
        }
Пример #9
0
        public string Encrypt(byte[] message, PgpPublicKey publicKey)
        {
            if (message == null || message.Length == 0)
            {
                throw new ArgumentException("Message must be supplied", nameof(message));
            }
            if (publicKey == null)
            {
                throw new ArgumentException("Public key must be supplied", nameof(publicKey));
            }

            byte[] processedData = Compress(message, PgpLiteralData.Console, CompressionAlgorithmTag.Zip);

            MemoryStream bOut   = new MemoryStream();
            Stream       output = new ArmoredOutputStream(bOut);


            PgpEncryptedDataGenerator encGen = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, true, new SecureRandom());

            encGen.AddMethod(publicKey);

            Stream encOut = encGen.Open(output, processedData.Length);

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

            output.Close();

            return(Encoding.UTF8.GetString(bOut.ToArray()));
        }
Пример #10
0
 public string Encrypt(string filename, byte[] data, PgpPublicKey publicKey)
 {
     using (MemoryStream encOut = new MemoryStream(), bOut = new MemoryStream()) {
         var comData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
         var cos     = comData.Open(bOut); // open it with the final destination
         var lData   = new PgpLiteralDataGenerator();
         var pOut    = lData.Open(
             cos,                    // the compressed output stream
             PgpLiteralData.Binary,
             filename,               // "filename" to store
             data.Length,            // length of clear data
             DateTime.UtcNow         // current time
             );
         pOut.Write(data, 0, data.Length);
         lData.Close();
         comData.Close();
         var cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, true, new SecureRandom());
         cPk.AddMethod(publicKey);
         byte[] bytes = bOut.ToArray();
         var    s     = new ArmoredOutputStream(encOut);
         var    cOut  = cPk.Open(s, bytes.Length);
         cOut.Write(bytes, 0, bytes.Length);  // obtain the actual bytes from the compressed stream
         cOut.Close();
         s.Close();
         encOut.Seek(0, SeekOrigin.Begin);
         var reader = new StreamReader(encOut);
         return(reader.ReadToEnd());
     }
 }
Пример #11
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());
                    }
        }
Пример #12
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 EncryptFileWithStreamKey(string inputFilePath, string outputFilePath, Stream publicKeyStream, bool armor = true, bool withIntegrityCheck = true)
        {
            if (string.IsNullOrEmpty(inputFilePath))
            {
                throw new ArgumentException("inputFilePath");
            }
            if (string.IsNullOrEmpty(outputFilePath))
            {
                throw new ArgumentException("inputFilePath");
            }

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

            using (Stream pkStream = publicKeyStream)
            {
                using (MemoryStream @out = new MemoryStream())
                {
                    if (CompressionAlgorithm != CompressionAlgorithm.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(PGPKeyHelper.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);
                            }
                        }
                    }
                }
            }
        }
Пример #13
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.WriteLine(e);

                Exception underlyingException = e.InnerException;

                if (underlyingException != null)
                {
                    Console.WriteLine(underlyingException.Message);

                    Console.WriteLine(underlyingException.StackTrace);
                }
            }
        }
Пример #14
0
        public String EncryptKeycode(String publicKeyStr, String unencryptedKeycode)
        {
            byte[] unencryptedByteArray = System.Text.Encoding.ASCII.GetBytes(unencryptedKeycode);
            byte[] decodedPublicKey     = System.Text.Encoding.ASCII.GetBytes(publicKeyStr);

            PgpPublicKey key = null;

            Stream decodedStream            = PgpUtilities.GetDecoderStream(new MemoryStream(decodedPublicKey));
            PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(decodedStream);

            foreach (PgpPublicKeyRing pgpPub in pubRings.GetKeyRings())
            {
                foreach (PgpPublicKey publicKey in pgpPub.GetPublicKeys())
                {
                    if (publicKey.IsEncryptionKey)
                    {
                        key = publicKey;
                        break;
                    }
                }
            }

            if (key == null)
            {
                throw new SendSafely.Exceptions.InvalidKeyException("Can't find encryption key in key ring.");
            }

            PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, true);

            cPk.AddMethod(key);

            PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator();

            // Write the data to a literal
            MemoryStream bOut;

            using (bOut = new MemoryStream())
            {
                using (Stream pOut = lData.Open(bOut, PgpLiteralData.Binary, PgpLiteralData.Console, unencryptedByteArray.Length, DateTime.Now))
                {
                    pOut.Write(unencryptedByteArray, 0, unencryptedByteArray.Length);
                }
            }
            lData.Close();

            byte[] bytes = bOut.ToArray();

            MemoryStream encOut = new MemoryStream();

            using (ArmoredOutputStream armoredOut = new ArmoredOutputStream(encOut))
            {
                using (Stream cOut = cPk.Open(armoredOut, bytes.Length))
                {
                    cOut.Write(bytes, 0, bytes.Length);
                }
            }

            return(System.Text.Encoding.Default.GetString(encOut.ToArray()));
        }
Пример #15
0
        } // End sub WriteOutputAndSign

        protected System.IO.Stream ChainEncryptedOut(System.IO.Stream outputStream)
        {
            PgpEncryptedDataGenerator encryptedDataGenerator;

            encryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.TripleDes, new SecureRandom());
            encryptedDataGenerator.AddMethod(m_encryptionKeys.PublicKey);
            return(encryptedDataGenerator.Open(outputStream, new byte[BufferSize]));
        } // End Sub ChainEncryptedOut
Пример #16
0
        private Stream ChEncryptedO(Stream oStream)
        {
            PgpEncryptedDataGenerator encryptedDataGen;

            encryptedDataGen = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.TripleDes, new SecureRandom());
            encryptedDataGen.AddMethod(mPgpKeys.PublicKey);
            return(encryptedDataGen.Open(oStream, new byte[BufferSize]));
        }
Пример #17
0
        private Stream ChainEncryptedOut(Stream outputStream, ChoPGPEncryptionKeys encryptionKeys, bool withIntegrityCheck)
        {
            PgpEncryptedDataGenerator encryptedDataGenerator;

            encryptedDataGenerator = new PgpEncryptedDataGenerator((SymmetricKeyAlgorithmTag)(int)SymmetricKeyAlgorithm, withIntegrityCheck, new SecureRandom());
            encryptedDataGenerator.AddMethod(encryptionKeys.PublicKey);
            return(encryptedDataGenerator.Open(outputStream, new byte[BufferSize]));
        }
Пример #18
0
        public void EncryptFile(FileInfo encryptedFile, FileInfo inputFile, string filename, char[] passPhrase, ISendSafelyProgress progress)
        {
            using var outStream = encryptedFile.OpenWrite();
            var cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, true);

            cPk.AddMethod(passPhrase, HashAlgorithmTag.Sha1);
            using var cOut = cPk.Open(outStream, new byte[1 << 16]);
            WriteFileToLiteralData(cOut, PgpLiteralData.Binary, inputFile, filename, inputFile.Length);
        }
Пример #19
0
        /// <summary>
        /// Helper for getting encryption stream
        /// </summary>
        /// <param name="stream">Stream to chain for encryption</param>
        /// <param name="input">Task settings</param>
        /// <returns>Encryption chained stream</returns>
        internal static Stream GetEncryptionStream(Stream stream, PgpEncryptInput input)
        {
            SymmetricKeyAlgorithmTag  algorithmTag           = input.EncryptionAlgorithm.ConvertEnum <SymmetricKeyAlgorithmTag>();
            PgpPublicKey              publicKey              = ReadPublicKey(input.PublicKeyFile);
            PgpEncryptedDataGenerator encryptedDataGenerator = new PgpEncryptedDataGenerator(algorithmTag, input.UseIntegrityCheck, new SecureRandom());

            encryptedDataGenerator.AddMethod(publicKey);
            return(encryptedDataGenerator.Open(stream, new byte[PgpTasks.EncryptBufferSize]));
        }
        private Stream encrypt(Stream output)
        {
            PgpEncryptedDataGenerator pgpEncDataGen = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Twofish, new SecureRandom());

            pgpEncDataGen.AddMethod(_pgpKeys.PGPPublicKey);
            Stream encryptedOutput = pgpEncDataGen.Open(output, new byte[BufferSize]);

            return(encryptedOutput);
        }
Пример #21
0
        private Stream chainEncryptedOut(Stream outputStream)
        {
            PgpEncryptedDataGenerator encryptedDataGenerator;

            encryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.TripleDes, new SecureRandom());
            encryptedDataGenerator.AddMethod(mEncryptionKeys.PublicKey);

            return(encryptedDataGenerator.Open(outputStream, new byte[bufferSize]));
        }
Пример #22
0
        private static Stream EncryptOut(Stream stream, string publicKey)
        {
            var key       = GetEncryptionKey(publicKey);
            var encryptor = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, true);

            encryptor.AddMethod(key);

            return(encryptor.Open(stream, new byte[BUFFER_SIZE]));
        }
Пример #23
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 Encrypt(Stream inputStream, Stream outputStream, Stream publicKeyStream,
                            bool armor = true, bool withIntegrityCheck = true)
        {
            if (inputStream == null)
            {
                throw new ArgumentException(nameof(inputStream));
            }
            if (outputStream == null)
            {
                throw new ArgumentException(nameof(outputStream));
            }
            if (publicKeyStream == null)
            {
                throw new ArgumentException(nameof(publicKeyStream));
            }

            Stream pkStream = publicKeyStream;

            using (MemoryStream @out = new MemoryStream())
            {
                if (CompressionAlgorithm != ChoCompressionAlgorithm.Uncompressed)
                {
                    PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator((CompressionAlgorithmTag)(int)CompressionAlgorithm);
                    ChoPGPUtility.WriteStreamToLiteralData(comData.Open(@out), FileTypeToChar(), inputStream, GetFileName(inputStream));
                    comData.Close();
                }
                else
                {
                    ChoPGPUtility.WriteStreamToLiteralData(@out, FileTypeToChar(), inputStream, GetFileName(inputStream));
                }

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

                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);
                    }
                }
            }
        }
        /// <summary>
        /// Takes a File and Encrypts it using the PGP Public Key.
        /// Outputs a file to your Output file
        /// </summary>
        /// <param name="inputFile">File you wish to encrypt</param>
        /// <param name="outputFile">File name to output too</param>
        /// <param name="armor">Armor or Not to Armor the stream during encryption</param>
        /// <param name="integrityCheck">Adds a PGP check bit to insure the integrity of the data</param>
        public static void EncryptFile(FileInfo inputFile, string outputFile = "Encrypted.txt", bool armor = true, bool integrityCheck = true)
        {
            #region inputValidation
            if (inputFile == null)
            {
                throw new ArgumentNullException(nameof(inputFile));
            }

            if (string.IsNullOrWhiteSpace(outputFile))
            {
                throw new ArgumentNullException(nameof(outputFile));
            }

            if (!IsPublicKeyPopulated)
            {
                throw new Exception(PublicKeyNotPopulatedText);
            }
            #endregion


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

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

                dataGenerator.AddMethod(_populatedPublicKey);
                var dataBytes = outputBytes.ToArray();

                using (Stream outputStream = File.Create(outputFile))
                {
                    try
                    {
                        if (armor)
                        {
                            using (var armoredStream = new ArmoredOutputStream(outputStream))
                            {
                                WriteStream(dataGenerator.Open(armoredStream, dataBytes.Length), ref dataBytes);
                            }
                        }
                        else
                        {
                            WriteStream(dataGenerator.Open(outputStream, dataBytes.Length), ref dataBytes);
                        }
                    }
                    catch (Exception e)
                    {
                        throw new Exception("Unable to Encrypt File", e);
                    }
                }
            }
        }
Пример #25
0
        /// <summary>
        ///     Encrypts an input file stream given the provided Public Key File.
        /// </summary>
        /// <param name="outputFileStream">File Stream of the new encrypted output file.</param>
        /// <param name="inputFilePath">Path of existing unencrypted input file.</param>
        /// <param name="publicKey">PgpPublicKey that will be used to encrypt the file.</param>
        /// <param name="armor">Use ASCII Armor</param>
        /// <param name="withIntegrityCheck">Include Integrity Check</param>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="FileNotFoundException"></exception>
        private static void EncryptFile(Stream outputFileStream, string inputFilePath, PgpPublicKey publicKey, bool armor = true, bool withIntegrityCheck = true)
        {
            // Parameter Checks
            if (String.IsNullOrEmpty(inputFilePath))
            {
                throw new ArgumentException("Input File Name Parameter is invalid.");
            }

            if (!File.Exists(inputFilePath))
            {
                throw new FileNotFoundException("Input File does not exist.");
            }

            if (armor)
            {
                outputFileStream = new ArmoredOutputStream(outputFileStream);
            }

            try
            {
                PgpEncryptedDataGenerator _encryptedDataGen = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());

                _encryptedDataGen.AddMethod(publicKey);

                Stream _encryptedOutStream = _encryptedDataGen.Open(outputFileStream, new byte[1 << 16]);

                PgpCompressedDataGenerator _compressedDataGen = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);

                FileInfo inputFile       = new FileInfo(inputFilePath);
                Stream   inputFileStream = File.OpenRead(inputFile.FullName);

                PgpCustomUtilities.WriteStreamToLiteralData(_compressedDataGen.Open(_encryptedOutStream), PgpLiteralData.Binary, inputFileStream, inputFile.Name);

                _compressedDataGen.Close();
                _encryptedOutStream.Dispose();
                inputFileStream.Dispose();

                if (armor)
                {
                    outputFileStream.Dispose();
                }
            }
            catch (PgpException ex)
            {
                Console.Error.WriteLine(ex);

                Exception underlyingException = ex.InnerException;
                if (underlyingException != null)
                {
                    Console.Error.WriteLine(underlyingException.Message);
                    Console.Error.WriteLine(underlyingException.StackTrace);
                }
            }
        }
Пример #26
0
        void EncryptFile()
        {
            try
            {
                var InStream  = InFile.OpenRead();
                var OutStream = OutFile.OpenWrite();

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

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

                MemoryStream bOut = new MemoryStream();
                if (Compress)
                {
                    PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.ZLib);
                    WriteStreamToLiteralData(comData.Open(bOut), PgpLiteralData.Binary, InStream);
                    comData.Close();
                }
                else
                {
                    WriteStreamToLiteralData(bOut, PgpLiteralData.Binary, InStream);
                }

                byte[] bytes = bOut.ToArray();

                if (Armor)
                {
                    using (ArmoredOutputStream armoredStream = new ArmoredOutputStream(OutStream))
                    {
                        using (Stream cOut = encGen.Open(armoredStream, bytes.Length))
                        {
                            cOut.Write(bytes, 0, bytes.Length);
                        }
                    }
                }
                else
                {
                    using (Stream cOut = encGen.Open(OutStream, bytes.Length))
                    {
                        cOut.Write(bytes, 0, bytes.Length);
                    }
                }

                OutStream.Close();
            }
            catch
            {
                throw;
            }
        }
Пример #27
0
        private Stream ChainEncryptedOut(Stream outputStream, EncryptionKeys encryptionKeys, bool withIntegrityCheck)
        {
            PgpEncryptedDataGenerator encryptedDataGenerator;

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

            if (encryptionKeys.PublicKey != null)
            {
                encryptedDataGenerator.AddMethod(encryptionKeys.PublicKey);
            }
            else if (encryptionKeys.PublicKeys != null)
            {
                foreach (PgpPublicKey publicKey in encryptionKeys.PublicKeys)
                {
                    encryptedDataGenerator.AddMethod(publicKey);
                }
            }

            return(encryptedDataGenerator.Open(outputStream, new byte[BufferSize]));
        }
Пример #28
0
        public static void Encrypt(byte[] clearData, PgpPublicKey encKey, string fileName, FileStream fos, bool withIntegrityCheck, bool armor)
        {
            if (fileName == null)
            {
                fileName = PgpLiteralData.Console;
            }

            MemoryStream encOut = new MemoryStream();

            Stream outPut = encOut;

            if (armor)
            {
                outPut = new Org.BouncyCastle.Bcpg.ArmoredOutputStream(outPut);
            }

            MemoryStream bOut = new MemoryStream();

            PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
            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, PgpLiteralData.Binary, fileName, clearData.Length, DateTime.Now);

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

            PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new Org.BouncyCastle.Security.SecureRandom());

            cPk.AddMethod(encKey);

            byte[] bytes = bOut.ToArray();

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

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

            outPut.Close();

            //FileStream fileStream = new FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            // Writes a block of bytes to this stream using data from
            // a byte array.
            fos.Write(encOut.ToArray(), 0, encOut.ToArray().Length);

            // close file stream
            fos.Close();
        }
Пример #29
0
        private Stream EncryptionStream(Stream outputStream)
        {
            if (PublicKey == null)
            {
                return(outputStream);
            }

            var encryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithm, WithIntegrityPacket);

            encryptedDataGenerator.AddMethod(PublicKey);
            return(encryptedDataGenerator.Open(outputStream, new byte[1 << 16]));
        }
Пример #30
0
        /// <summary>
        /// Encrypt data to a set of recipients
        /// </summary>
        /// <param name="data">Data to encrypt</param>
        /// <param name="recipients">List of email addresses</param>
        /// <param name="recipients">Headers to add to ascii armor</param>
        /// <returns>Returns ascii armored encrypted data</returns>
        public string Encrypt(byte[] data, IList <string> recipients, Dictionary <string, string> headers)
        {
            Context = new CryptoContext(Context);

            var compressedData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
            var literalData    = new PgpLiteralDataGenerator();
            var cryptData      = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, true, new SecureRandom());

            foreach (var recipient in recipients)
            {
                var recipientKey = GetPublicKeyForEncryption(recipient);
                if (recipientKey == null)
                {
                    throw new PublicKeyNotFoundException("Error, unable to find recipient key \"" + recipient + "\".");
                }

                cryptData.AddMethod(recipientKey);
            }

            using (var sout = new MemoryStream())
            {
                using (var armoredOut = new ArmoredOutputStream(sout))
                {
                    foreach (var header in headers)
                    {
                        armoredOut.SetHeader(header.Key, header.Value);
                    }

                    using (var clearOut = new MemoryStream())
                    {
                        using (var compressedOut = compressedData.Open(clearOut))
                            using (var literalOut = literalData.Open(
                                       compressedOut,
                                       PgpLiteralData.Binary,
                                       "email",
                                       data.Length,
                                       DateTime.UtcNow))
                            {
                                literalOut.Write(data, 0, data.Length);
                            }

                        var clearData = clearOut.ToArray();

                        using (var encryptOut = cryptData.Open(armoredOut, clearData.Length))
                        {
                            encryptOut.Write(clearData, 0, clearData.Length);
                        }
                    }
                }

                return(ASCIIEncoding.ASCII.GetString(sout.ToArray()));
            }
        }
Пример #31
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.");
//					}
                }
            }
		}
Пример #32
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");
			}
		}
Пример #33
0
        private void EncryptDecryptTest()
        {
            SecureRandom random = SecureRandom.GetInstance("SHA1PRNG");

            byte[] text = Encoding.ASCII.GetBytes("hello world!");

            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDH");
            keyGen.Init(new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, random));

            AsymmetricCipherKeyPair kpEnc = keyGen.GenerateKeyPair();

            PgpKeyPair ecdhKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ECDH, kpEnc, DateTime.UtcNow);

            PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator();
            MemoryStream ldOut = new MemoryStream();
            Stream pOut = lData.Open(ldOut, PgpLiteralDataGenerator.Utf8, PgpLiteralData.Console, text.Length, DateTime.UtcNow);

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

            pOut.Close();

            byte[] data = ldOut.ToArray();

            MemoryStream cbOut = new MemoryStream();

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

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

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

            cOut.Close();

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

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

            PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0];

            Stream clear = encP.GetDataStream(ecdhKeyPair.PrivateKey);

            pgpF = new PgpObjectFactory(clear);

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

            clear = ld.GetInputStream();
            MemoryStream bOut = new MemoryStream();

            int ch;
            while ((ch = clear.ReadByte()) >= 0)
            {
                bOut.WriteByte((byte)ch);
            }

            byte[] output = bOut.ToArray();

            if (!AreEqual(output, text))
            {
                Fail("wrong plain text in Generated packet");
            }
        }
Пример #34
0
        public override void PerformTest()
        {
            //
            // Read the public key
            //
            PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey);

            AsymmetricKeyParameter pubKey = pgpPub.GetPublicKey().GetKey();

            IEnumerator enumerator = pgpPub.GetPublicKey().GetUserIds().GetEnumerator();
            enumerator.MoveNext();
            string uid = (string) enumerator.Current;


            enumerator = pgpPub.GetPublicKey().GetSignaturesForId(uid).GetEnumerator();
            enumerator.MoveNext();
            PgpSignature sig = (PgpSignature) enumerator.Current;

            sig.InitVerify(pgpPub.GetPublicKey());

            if (!sig.VerifyCertification(uid, pgpPub.GetPublicKey()))
            {
                Fail("failed to verify certification");
            }

            //
            // write a public key
            //
            MemoryStream bOut = new UncloseableMemoryStream();
            BcpgOutputStream pOut = new BcpgOutputStream(bOut);

            pgpPub.Encode(pOut);

            if (!Arrays.AreEqual(bOut.ToArray(), testPubKey))
            {
                Fail("public key rewrite failed");
            }

            //
            // Read the public key
            //
            PgpPublicKeyRing pgpPubV3 = new PgpPublicKeyRing(testPubKeyV3);
            AsymmetricKeyParameter pubKeyV3 = pgpPub.GetPublicKey().GetKey();

            //
            // write a V3 public key
            //
            bOut = new UncloseableMemoryStream();
            pOut = new BcpgOutputStream(bOut);

            pgpPubV3.Encode(pOut);

            //
            // Read a v3 private key
            //
            char[] passP = "FIXCITY_QA".ToCharArray();

            {
                PgpSecretKeyRing pgpPriv2 = new PgpSecretKeyRing(testPrivKeyV3);
                PgpSecretKey pgpPrivSecretKey = pgpPriv2.GetSecretKey();
                PgpPrivateKey pgpPrivKey2 = pgpPrivSecretKey.ExtractPrivateKey(passP);

                //
                // write a v3 private key
                //
                bOut = new UncloseableMemoryStream();
                pOut = new BcpgOutputStream(bOut);

                pgpPriv2.Encode(pOut);

                byte[] result = bOut.ToArray();
                if (!Arrays.AreEqual(result, testPrivKeyV3))
                {
                    Fail("private key V3 rewrite failed");
                }
            }

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

            //
            // write a private key
            //
            bOut = new UncloseableMemoryStream();
            pOut = new BcpgOutputStream(bOut);

            pgpPriv.Encode(pOut);

            if (!Arrays.AreEqual(bOut.ToArray(), testPrivKey))
            {
                Fail("private key rewrite failed");
            }

            //
            // test encryption
            //
            IBufferedCipher c = CipherUtilities.GetCipher("RSA");

//                c.Init(Cipher.ENCRYPT_MODE, pubKey);
            c.Init(true, pubKey);

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

//                c.Init(Cipher.DECRYPT_MODE, pgpPrivKey.GetKey());
            c.Init(false, pgpPrivKey.Key);

            outBytes = c.DoFinal(outBytes);

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

            //
            // 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(pgpPub.GetPublicKey(ops.KeyId));

            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");
            }

            //
            // encrypted message - read subkey
            //
            pgpPriv = new PgpSecretKeyRing(subKey);

            //
            // encrypted message
            //
            byte[] text = Encoding.ASCII.GetBytes("hello world!\n");

            PgpObjectFactory pgpF = new PgpObjectFactory(enc1);

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

            PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0];

            pgpPrivKey = pgpPriv.GetSecretKey(encP.KeyId).ExtractPrivateKey(pass);

            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");
            }

            //
            // encrypt - short message
            //
            byte[] shortText = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' };

            MemoryStream cbOut = new UncloseableMemoryStream();
            PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, new SecureRandom());
            PgpPublicKey puK = pgpPriv.GetSecretKey(encP.KeyId).PublicKey;

            cPk.AddMethod(puK);

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

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

            cOut.Close();

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

            encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

            encP = (PgpPublicKeyEncryptedData)encList[0];

            pgpPrivKey = pgpPriv.GetSecretKey(encP.KeyId).ExtractPrivateKey(pass);

            if (encP.GetSymmetricAlgorithm(pgpPrivKey) != SymmetricKeyAlgorithmTag.Cast5)
            {
                Fail("symmetric algorithm mismatch");
            }

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

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

            //
            // encrypt
            //
            cbOut = new UncloseableMemoryStream();
            cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, new SecureRandom());
            puK = pgpPriv.GetSecretKey(encP.KeyId).PublicKey;

            cPk.AddMethod(puK);

            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 = pgpPriv.GetSecretKey(encP.KeyId).ExtractPrivateKey(pass);

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

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

            //
            // read public key with sub key.
            //
            pgpF = new PgpObjectFactory(subPubKey);
            object o;
            while ((o = pgpFact.NextPgpObject()) != null)
            {
                // TODO Should something be tested here?
                // Console.WriteLine(o);
            }

            //
            // key pair generation - CAST5 encryption
            //
            char[] passPhrase = "hello".ToCharArray();
            IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("RSA");
            RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters(
                BigInteger.ValueOf(0x10001), new SecureRandom(), 1024, 25);

            kpg.Init(genParam);


            AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();

            PgpSecretKey secretKey = new PgpSecretKey(
                PgpSignature.DefaultCertification,
                PublicKeyAlgorithmTag.RsaGeneral,
                kp.Public,
                kp.Private,
                DateTime.UtcNow,
                "fred",
                SymmetricKeyAlgorithmTag.Cast5,
                passPhrase,
                null,
                null,
                new SecureRandom()
                );

            PgpPublicKey key = secretKey.PublicKey;


            enumerator = key.GetUserIds().GetEnumerator();
            enumerator.MoveNext();
            uid = (string) enumerator.Current;


            enumerator = key.GetSignaturesForId(uid).GetEnumerator();
            enumerator.MoveNext();
            sig = (PgpSignature) enumerator.Current;

            sig.InitVerify(key);

            if (!sig.VerifyCertification(uid, key))
            {
                Fail("failed to verify certification");
            }

            pgpPrivKey = secretKey.ExtractPrivateKey(passPhrase);

            key = PgpPublicKey.RemoveCertification(key, uid, sig);

            if (key == null)
            {
                Fail("failed certification removal");
            }

            byte[] keyEnc = key.GetEncoded();

            key = PgpPublicKey.AddCertification(key, uid, sig);

            keyEnc = key.GetEncoded();

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

            sGen.InitSign(PgpSignature.KeyRevocation, secretKey.ExtractPrivateKey(passPhrase));

            sig = sGen.GenerateCertification(key);

            key = PgpPublicKey.AddCertification(key, sig);

            keyEnc = key.GetEncoded();

            PgpPublicKeyRing tmpRing = new PgpPublicKeyRing(keyEnc);

            key = tmpRing.GetPublicKey();

            IEnumerator sgEnum = key.GetSignaturesOfType(PgpSignature.KeyRevocation).GetEnumerator();
            sgEnum.MoveNext();
            sig = (PgpSignature) sgEnum.Current;

            sig.InitVerify(key);

            if (!sig.VerifyCertification(key))
            {
                Fail("failed to verify revocation certification");
            }

            //
            // use of PgpKeyPair
            //
            PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.RsaGeneral,
                kp.Public, kp.Private, DateTime.UtcNow);

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

            k1.GetEncoded();

            MixedTest(k2, k1);

            //
            // key pair generation - AES_256 encryption.
            //
            kp = kpg.GenerateKeyPair();

            secretKey = new PgpSecretKey(PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, kp.Public, kp.Private, DateTime.UtcNow, "fred", SymmetricKeyAlgorithmTag.Aes256, passPhrase, null, null, new SecureRandom());

            secretKey.ExtractPrivateKey(passPhrase);

            secretKey.Encode(new UncloseableMemoryStream());

            //
            // secret key password changing.
            //
            const string newPass = "******";

            secretKey = PgpSecretKey.CopyWithNewPassword(secretKey, passPhrase, newPass.ToCharArray(), secretKey.KeyEncryptionAlgorithm, new SecureRandom());

            secretKey.ExtractPrivateKey(newPass.ToCharArray());

            secretKey.Encode(new UncloseableMemoryStream());

            key = secretKey.PublicKey;

            key.Encode(new UncloseableMemoryStream());


            enumerator = key.GetUserIds().GetEnumerator();
            enumerator.MoveNext();
            uid = (string) enumerator.Current;


            enumerator = key.GetSignaturesForId(uid).GetEnumerator();
            enumerator.MoveNext();
            sig = (PgpSignature) enumerator.Current;

            sig.InitVerify(key);

            if (!sig.VerifyCertification(uid, key))
            {
                Fail("failed to verify certification");
            }

            pgpPrivKey = secretKey.ExtractPrivateKey(newPass.ToCharArray());

            //
            // signature generation
            //
            const string data = "hello world!";
            byte[] dataBytes = Encoding.ASCII.GetBytes(data);

            bOut = new UncloseableMemoryStream();

            MemoryStream testIn = new MemoryStream(dataBytes, false);

            sGen = new PgpSignatureGenerator(
                PublicKeyAlgorithmTag.RsaGeneral, 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);

            // TODO Need a stream object to automatically call Update?
            // (via ISigner implementation of PgpSignatureGenerator)
            while ((ch = testIn.ReadByte()) >= 0)
            {
                lOut.WriteByte((byte)ch);
                sGen.Update((byte)ch);
            }

            lOut.Close();

            sGen.Generate().Encode(bcOut);

            bcOut.Close();

            //
            // verify generated signature
            //
            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(secretKey.PublicKey);

            // TODO Need a stream object to automatically call Update?
            // (via ISigner implementation of PgpSignatureGenerator)
            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
            }

            p3 = (PgpSignatureList)pgpFact.NextPgpObject();

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

            //
            // signature generation - version 3
            //
            bOut = new UncloseableMemoryStream();

            testIn = new MemoryStream(dataBytes);
            PgpV3SignatureGenerator sGenV3 = new PgpV3SignatureGenerator(
                PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

            cGen = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);

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

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

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

            // TODO Need a stream object to automatically call Update?
            // (via ISigner implementation of PgpSignatureGenerator)
            while ((ch = testIn.ReadByte()) >= 0)
            {
                lOut.WriteByte((byte) ch);
                sGen.Update((byte)ch);
            }

            lOut.Close();

            sGen.Generate().Encode(bcOut);

            bcOut.Close();

            //
            // verify generated signature
            //
            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(secretKey.PublicKey);

            // TODO Need a stream object to automatically call Update?
            // (via ISigner implementation of PgpSignatureGenerator)
            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
            }

            p3 = (PgpSignatureList)pgpFact.NextPgpObject();

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

            //
            // extract PGP 8 private key
            //
            pgpPriv = new PgpSecretKeyRing(pgp8Key);

            secretKey = pgpPriv.GetSecretKey();

            pgpPrivKey = secretKey.ExtractPrivateKey(pgp8Pass);

            //
            // other sig tests
            //
            PerformTestSig(HashAlgorithmTag.Sha256, secretKey.PublicKey, pgpPrivKey);
            PerformTestSig(HashAlgorithmTag.Sha384, secretKey.PublicKey, pgpPrivKey);
            PerformTestSig(HashAlgorithmTag.Sha512, secretKey.PublicKey, pgpPrivKey);
            FingerPrintTest();
            ExistingEmbeddedJpegTest();
            EmbeddedJpegTest();
        }
Пример #35
0
        private void MixedTest(
            PgpPrivateKey	pgpPrivKey,
            PgpPublicKey	pgpPubKey)
        {
            byte[] text = Encoding.ASCII.GetBytes("hello world!\n");

            //
            // literal data
            //
            MemoryStream bOut = new MemoryStream();
            PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();
            Stream lOut = lGen.Open(
                bOut,
                PgpLiteralData.Binary,
                PgpLiteralData.Console,
                text.Length,
                DateTime.UtcNow);

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

            lGen.Close();

            byte[] bytes = bOut.ToArray();

            PgpObjectFactory f = new PgpObjectFactory(bytes);
            CheckLiteralData((PgpLiteralData)f.NextPgpObject(), text);

            MemoryStream bcOut = new MemoryStream();

            PgpEncryptedDataGenerator encGen = new PgpEncryptedDataGenerator(
                SymmetricKeyAlgorithmTag.Aes128,
                true,
                new SecureRandom());

            encGen.AddMethod(pgpPubKey);

            encGen.AddMethod("password".ToCharArray(), HashAlgorithmTag.Sha1);

            Stream cOut = encGen.Open(bcOut, bytes.Length);

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

            cOut.Close();

            byte[] encData = bcOut.ToArray();

            //
            // asymmetric
            //
            PgpObjectFactory pgpF = new PgpObjectFactory(encData);

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

            PgpPublicKeyEncryptedData  encP = (PgpPublicKeyEncryptedData)encList[0];

            Stream clear = encP.GetDataStream(pgpPrivKey);

            PgpObjectFactory pgpFact = new PgpObjectFactory(clear);

            CheckLiteralData((PgpLiteralData)pgpFact.NextPgpObject(), text);

            //
            // PBE
            //
            pgpF = new PgpObjectFactory(encData);

            encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

            PgpPbeEncryptedData encPbe = (PgpPbeEncryptedData) encList[1];

            clear = encPbe.GetDataStream("password".ToCharArray());

            pgpF = new PgpObjectFactory(clear);

            CheckLiteralData((PgpLiteralData) pgpF.NextPgpObject(), text);
        }