Ejemplo n.º 1
0
        /// <summary>
        /// Decrypt a stream
        /// </summary>
        /// <param name="encrypt"></param>
        /// <param name="inputStream">readable stream with encrypted data</param>
        /// <param name="outputStream">writable stream for decrypted data</param>
        /// <param name="bufferSize"></param>
        /// <exception cref="ArgumentException"></exception>
        public static void DecryptStream(this EasyEncrypt encrypt, Stream inputStream, Stream outputStream,
                                         int bufferSize = DefaultBufferSize)
        {
            if (encrypt == null)
            {
                throw new ArgumentException("Can't encrypt data: encrypt class is null");
            }
            if (inputStream == null || !inputStream.CanRead)
            {
                throw new ArgumentException("Can't encrypt data: inputStream is not readable");
            }
            if (outputStream == null || !outputStream.CanWrite)
            {
                throw new ArgumentException("Can't encrypt data: output stream is not writable");
            }

            byte[] iv = new byte[encrypt.Algorithm.IV.Length];
            inputStream.Read(iv, 0, iv.Length);
            encrypt.Algorithm.IV = iv;

            using var decrypter = encrypt.Algorithm.CreateDecryptor(encrypt.Algorithm.Key, encrypt.Algorithm.IV);
            using var cs        = new CryptoStream(inputStream, decrypter, CryptoStreamMode.Read);

            var buffer = new byte[bufferSize];
            int read;

            while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)
            {
                outputStream.Write(buffer, 0, read);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Decrypt a file
        /// </summary>
        /// <param name="encrypt">encrypted input file</param>
        /// <param name="fileIn">location of new decrypted file</param>
        /// <param name="fileOut"></param>
        /// <param name="bufferSize"></param>
        public static void DecryptFile(this EasyEncrypt encrypt, string fileIn, string fileOut,
                                       int bufferSize = DefaultBufferSize)
        {
            using var fileInStream  = new FileStream(fileIn, FileMode.Open);
            using var fileOutStream = new FileStream(fileOut, FileMode.Create);

            encrypt?.DecryptStream(fileInStream, fileOutStream, bufferSize);
        }