public string Encrypt(string toEncrypt, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = Encoding.UTF8.GetBytes(toEncrypt);
if (useHashing)
{
var hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(Encoding.UTF8.GetBytes("iloveit1208"));
}
else keyArray = Encoding.UTF8.GetBytes("iloveit1208");
var tdes = new TripleDESCryptoServiceProvider
{
Key = keyArray,
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};
ICryptoTransform cTransform = tdes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
Để giải mã chuỗi đã được mã hóa, ta dùng hàm Decrypt sau:
public string Decrypt(string toDecrypt, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);
if (useHashing)
{
var hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(Encoding.UTF8.GetBytes("iloveit1208"));
}
else keyArray = Encoding.UTF8.GetBytes("iloveit1208");
var tdes = new TripleDESCryptoServiceProvider
{
Key = keyArray,
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};
ICryptoTransform cTransform = tdes.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Encoding.UTF8.GetString(resultArray);
}
Ví dụ cách sử dung:
string s=”Chao mung cac ban den boi blog cua iloveit1208”;
string mahoa=Encrypt(s,true);
string giaima=Decrypt(mahoa,true);
Chúc các bạn thành công!