Mega Code Archive

 
Categories / C# Tutorial / Security
 

Create a CryptoStream using the MemoryStream

using System; using System.Security.Cryptography; using System.Text; using System.IO; class RC2Sample {     static void Main()     {         RC2 RC2alg = RC2.Create("RC2");         string sData = "this is a test.";         byte[] Data = EncryptTextToMemory(sData, RC2alg.Key, RC2alg.IV);         string Final = DecryptTextFromMemory(Data, RC2alg.Key, RC2alg.IV);         Console.WriteLine(Final);     }     public static byte[] EncryptTextToMemory(string Data,  byte[] Key, byte[] IV)     {          MemoryStream mStream = new MemoryStream();          RC2 RC2alg = RC2.Create();          CryptoStream cStream = new CryptoStream(mStream,RC2alg.CreateEncryptor(Key, IV),CryptoStreamMode.Write);          byte[] toEncrypt = new ASCIIEncoding().GetBytes(Data);          cStream.Write(toEncrypt, 0, toEncrypt.Length);          cStream.FlushFinalBlock();          byte[] ret = mStream.ToArray();          cStream.Close();          mStream.Close();          return ret;     }     public static string DecryptTextFromMemory(byte[] Data,  byte[] Key, byte[] IV)     {          MemoryStream msDecrypt = new MemoryStream(Data);          RC2 RC2alg = RC2.Create();          CryptoStream csDecrypt = new CryptoStream(msDecrypt,RC2alg.CreateDecryptor(Key, IV),CryptoStreamMode.Read);          byte[] fromEncrypt = new byte[Data.Length];          csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);          return new ASCIIEncoding().GetString(fromEncrypt);     } }