我的对象从数据库中出来后,我需要解密密码,我该如何实现呢?这是我的加密和解密代码:
public class EncryptionHelper {
public static string Encrypt(string strToEncrypt) {
try {
TripleDESCryptoServiceProvider objDESCrypto = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();
byte[] byteHash, byteBuff;
string strTempKey = Settings.Default.Keyword;
byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
objHashMD5 = null;
objDESCrypto.Key = byteHash;
objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB
byteBuff = ASCIIEncoding.ASCII.GetBytes(strToEncrypt);
return Convert.ToBase64String(objDESCrypto.CreateEncryptor().
TransformFinalBlock(byteBuff, 0, byteBuff.Length));
} catch (Exception ex) {
return strToEncrypt;
}
}
public static string Decrypt(string strEncrypted) {
try {
TripleDESCryptoServiceProvider objDESCrypto =
new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();
byte[] byteHash, byteBuff;
string strTempKey = Settings.Default.Keyword;
byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
objHashMD5 = null;
objDESCrypto.Key = byteHash;
objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB
byteBuff = Convert.FromBase64String(strEncrypted);
string strDecrypted = ASCIIEncoding.ASCII.GetString
(objDESCrypto.CreateDecryptor().TransformFinalBlock
(byteBuff, 0, byteBuff.Length));
objDESCrypto = null;
return strDecrypted;
} catch (Exception ex) {
return "Wrong Input. " + ex.Message;
}
}
}
这是我的实体:
public partial class S0Pin
{
public int ID { get; set; }
public string Serialnumber { get; set; }
public string Pin { get; set; }
public virtual User Creator { get; set; }
}
这是插入对象的方法
public bool AddS0Pin(S0Pin pin) {
log.Debug("add s0pin with serialnumber " + pin.Serialnumber);
var s0pin = S0Pin.SingleOrDefault(pn => pn.Serialnumber == pin.Serialnumber);
if (s0pin != null) {
s0pin.Pin = EncryptionHelper.Encrypt(pin.Pin);
} else {
this.S0Pin.Add(pin);
}
return this.SaveChanges() > 0;
}
取出数据库后如何解密数据?最好的方法是在实体中。