對稱式加解密 C#
說明 : 對稱式加解密意即可將加密後的字串做還原的動作.
適用平台:.Net Framework 1.0,1.1,2.0
using System.Text;
public string EnCode(string EnString) //將字串加密
{
byte[] Key = {123 , 123 , 123 , 123 , 123 , 123 , 123, 123};
byte[] IV = {123 , 123 , 123 , 123 , 123 , 123 , 123 , 123};
byte[] b = Encoding.UTF8.GetBytes(EnString);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
ICryptoTransform ict = des.CreateEncryptor(Key , IV);
byte[] outData = ict.TransformFinalBlock(b , 0 , b.Length);
return Convert.ToBase64String(outData); //回傳加密後的字串
}
public string DeCode(string DeString) //將字串解密
{
byte[] Key = {123 , 123 , 123 , 123 , 123 , 123 , 123, 123};
byte[] IV = {123 , 123 , 123 , 123 , 123 , 123 , 123 , 123};
byte[] b = Convert.FromBase64String(DeString);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
ICryptoTransform ict = des.CreateDecryptor(Key , IV);
byte[] outData = ict.TransformFinalBlock(b , 0 , b.Length);
return Encoding.UTF8.GetString(outData) ;//回傳解密後的字串
}
用此程式碼將"TestForEnCode"這字串加密後,就變為"KMdstO1vd6pgzf1nsk3CrA==",當然,解密後,也就變回"TestForEnCode"