using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;
class DESCSPSample
{
static void Main()
{
DESCryptoServiceProvider DESalg = new DESCryptoServiceProvider();
string sData = "this is a test.";
byte[] Data = EncryptTextToMemory(sData, DESalg.Key, DESalg.IV);
string Final = DecryptTextFromMemory(Data, DESalg.Key, DESalg.IV);
Console.WriteLine(Final);
}
public static byte[] EncryptTextToMemory(string Data, byte[] Key, byte[] IV)
{
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream,new DESCryptoServiceProvider().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);
CryptoStream csDecrypt = new CryptoStream(msDecrypt,new DESCryptoServiceProvider().CreateDecryptor(Key, IV),
CryptoStreamMode.Read);
byte[] fromEncrypt = new byte[Data.Length];
csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
return new ASCIIEncoding().GetString(fromEncrypt);
}
}