您可以简单地加密密码并将其存储在数据库中。当用户更改密码或首次注册时,只需对其进行加密。在检查验证时,加密文本框并检查两个字符串是否匹配。
当您需要知道密码时,请解密它们。
加密的示例代码如下所示
// Encrypt the text
public static string EncryptText(string strText)
{
return Encrypt(strText, "a#94tOc*"); // use any string to encrypt other than a#94tOc*
}
//The function used to encrypt the text
private static string Encrypt(string strText, string strEncrKey)
{
byte[] byKey = { };
byte[] IV = { 0X12, 0X34, 0X56, 0X78, 0X90, 0XAB, 0XCD, 0XEF };
byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = System.Text.Encoding.UTF8.GetBytes(strText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
同样用于解密,使用:
//Decrypt the text
public static string DecryptText(string strText)
{
return Decrypt(strText, "a#94tOc*"); // use same as encryption string
}
//The function used to decrypt the text
private static string Decrypt(string strText, string sDecrKey)
{
byte[] byKey = { };
byte[] IV = { 0X12, 0X34, 0X56, 0X78, 0X90, 0XAB, 0XCD, 0XEF };
byte[] inputByteArray = new byte[strText.Length + 1];
byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(strText.Replace(' ', '+'));
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
System.Text.Encoding encoding = System.Text.Encoding.UTF8;
return encoding.GetString(ms.ToArray());
}
所以基本上只需调用EncryptText(password) 进行加密和DecryptText(encrypted_password) 进行解密。