CSharp examples for System.Security.Cryptography:Encrypt Decrypt
Decrypts a stream with the specified symmetric provider.
using System.Security.Cryptography; using System.IO;// w ww. j a v a 2s.c o m using System; public class Main{ /// <summary> /// Decrypts a stream with the specified symmetric provider. /// </summary> /// <param name="inStream">The stream to decrypt.</param> /// <param name="provider">The cryptographic provider to use for encrypting.</param> /// <returns>Plaintext stream ready to be read.</returns> public static Stream GetDecryptedStream(Stream inStream, SymmetricAlgorithm provider) { // Make sure we got valid input if (inStream == null) throw new ArgumentNullException("Invalid stream.", "inStream"); if (provider == null) throw new ArgumentNullException("Invalid provider.", "provider"); // Create the input and output streams CryptoStream decryptStream = new CryptoStream(inStream, provider.CreateDecryptor(), CryptoStreamMode.Read); MemoryStream outStream = new MemoryStream(); // Read the stream and write it to the output. Note that we're depending // on the fact that ~CryptoStream does not close the underlying stream. int numBytes; byte [] inputBytes = new byte[_bufferSize]; while((numBytes = decryptStream.Read(inputBytes, 0, inputBytes.Length)) != 0) { outStream.Write(inputBytes, 0, numBytes); } // Go to the beginning of the decrypted stream and return it outStream.Position = 0; return outStream; } }