CSharp examples for System.Security.Cryptography:Encrypt Decrypt
Encrypts a stream with the specified symmetric provider. The returned stream is at position zero and ready to be read.
using System.Security.Cryptography; using System.IO;// www . j a va 2s .co m using System; public class Main{ /// <summary> /// Encrypts a stream with the specified symmetric provider. The returned stream /// is at position zero and ready to be read. /// </summary> /// <param name="inStream">The stream to encrypt.</param> /// <param name="provider">The cryptographic provider to use for encryption.</param> /// <returns>Encrypted stream ready to be read.</returns> public static Stream GetEncryptedStream(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 output stream MemoryStream outStream = new MemoryStream(); CryptoStream encryptStream = new CryptoStream(outStream, provider.CreateEncryptor(), CryptoStreamMode.Write); // Encrypt the stream by reading all bytes from the input stream and // writing them to the output encryption stream. 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 = inStream.Read(inputBytes, 0, inputBytes.Length)) != 0) { encryptStream.Write(inputBytes, 0, numBytes); } encryptStream.FlushFinalBlock(); // Go back to the beginning of the newly encrypted stream and return it outStream.Position = 0; return outStream; } }