Thursday, February 3, 2011

DES encryption in C#

const string DESKey = "AQWSEDRF";
const string DESIV = "HGFEDCBA";

public static string DESDecrypt(string stringToDecrypt)
{
byte[] key;
byte[] IV;
byte[] inputByteArray;
key = Convert2ByteArray(DESKey);
IV = Convert2ByteArray(DESIV);
int len = stringToDecrypt.Length;
inputByteArray = Convert.FromBase64String(stringToDecrypt);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
try
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
Encoding encoding = Encoding.UTF8;
return encoding.GetString(ms.ToArray());
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
ms.Close();
cs.Close();
}
}

public static string DESEncrypt(string stringToEncrypt)
{
byte[] key;
byte[] IV;
byte[] inputByteArray;
key = Convert2ByteArray(DESKey);
IV = Convert2ByteArray(DESIV);
inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
try
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
ms.Close();
cs.Close();
}
}

static byte[] Convert2ByteArray(string strInput)
{
int intCounter; char[] arrChar;
arrChar = strInput.ToCharArray();
byte[] arrByte = new byte[arrChar.Length];
for (intCounter = 0; intCounter < arrByte.Length; intCounter++)
arrByte[intCounter] = Convert.ToByte(arrChar[intCounter]);
return arrByte;
}

2 comments:

 
Locations of visitors to this page