Esempio n. 1
0
        public Stream Encrypt(out byte[] dataKey, Stream plaintextStream, IDictionary <string, string> context)
        {
            byte[] plaintextKey;
            _dataKeyProvider.GenerateKey(_config.KeyBits, out plaintextKey, out dataKey, context);

            ISymmetricAlgorithm algo = null;

            try
            {
                algo     = _algorithmFactory.CreateAlgorithm(_config);
                algo.Key = plaintextKey;
                algo.GenerateIV();

                // All these hoops with the concatenated streams, StreamWithDisposable, etc.
                // are to support: using (Stream foo = provider.Encrypt(...)) {...}
                ICryptoTransform encryptor    = algo.CreateEncryptor();
                Stream           ivStream     = new MemoryStream(algo.IV);
                Stream           cryptoStream = new CryptoStream(plaintextStream, encryptor, CryptoStreamMode.Read);
                Stream           streamPair   = new ConcatenatedStream(ivStream, cryptoStream);

                // when this stream is disposed, so will be all of its constituent streams,
                // plus the algorithm and the encryptor.
                return(new StreamWithDisposables(streamPair, new IDisposable[] { algo, encryptor }));
            }
            catch (Exception e)
            {
                // If we had trouble creating the stream, destroy the algorithm to prevent the key leaking.
                if (algo != null)
                {
                    try
                    {
                        algo.Dispose();
                    }
                    catch (Exception disposalException)
                    {
                        throw new AggregateException(e, disposalException);
                    }
                }
                throw;
            }
        }
 public static ISymmetricAlgorithm CreateAlgorithm(this IAlgorithmFactory self, IEnvelopeCryptoConfig config)
 {
     return(self.CreateAlgorithm(config.AlgorithmName, config.KeyBits, config.Mode, config.Padding));
 }