Tuesday, November 20, 2007

Functions for encrypting and decrypting using DES

string strResult;
byte[] KEY_64 ={42, 16, 93, 156, 78, 4, 218, 32};
byte[] IV_64={55, 103, 246, 79, 36, 99, 167, 3};

public string encrypt(string strInput)
{
DESCryptoServiceProvider cryptoProvider=new DESCryptoServiceProvider();
MemoryStream ms=new MemoryStream();
CryptoStream cs=new CryptoStream(ms,cryptoProvider.CreateEncryptor(KEY_64, IV_64),CryptoStreamMode.Write);
StreamWriter sw=new StreamWriter(cs);
sw.Write(strInput);
sw.Flush();
cs.Flush();
cs.FlushFinalBlock();
ms.Flush();
strResult=Convert.ToBase64String(ms.GetBuffer(),0,Convert.ToInt32(ms.Length));
return strResult;
}

public string decrypt(string strinput)
{
DESCryptoServiceProvider cryptoProvider=new DESCryptoServiceProvider();
byte[] buffer=Convert.FromBase64String(strinput.Trim());
MemoryStream ms=new MemoryStream(buffer);
CryptoStream cs=new CryptoStream(ms,cryptoProvider.CreateDecryptor(KEY_64, IV_64),CryptoStreamMode.Read);
StreamReader sr=new StreamReader(cs);
strResult = sr.ReadToEnd();
return strResult;
}

No comments: