這是參考自Jeff隨手記。我將他稍作修改可以讓Key與initial vector可以直接吃字串。解密失敗時會產生exception,可以作為檢測該密碼是否合法。
public string EncodeString(string EnString){
byte[] Key = Encoding.UTF8.GetBytes("xxxxxxxx");
byte[] IV = Encoding.UTF8.GetBytes("yyyyyyyy");
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 DecodeString(string DeString){ byte[] Key = Encoding.UTF8.GetBytes("xxxxxxxx");
byte[] IV = Encoding.UTF8.GetBytes("yyyyyyyy");
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);
}
資料來源:
[1] 對稱式加解密 C#
沒有留言:
張貼留言