从数据库中解密加密值
本文关键字:加密 解密 数据库 | 更新日期: 2023-09-27 18:09:50
我想在数据库中保存加密值,同时从数据库中获取值,我想解密并在UI中显示值。下面是我使用的代码
private string Decryptdata(string encryptpwd)
{
string decryptpwd = string.Empty;
UTF8Encoding encodepwd = new UTF8Encoding();
Decoder Decode = encodepwd.GetDecoder();
encryptpwd = encryptpwd.Replace(" ", "+");
byte[] todecode_byte = Convert.FromBase64String(encryptpwd);
int charCount = Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
decryptpwd = new String(decoded_char);
return decryptpwd;
}
但我得到错误作为无效长度为Base-64字符数组。我正在使用c#.net
加密功能:
Encryptdata(string password) {
string strmsg = string.Empty;
byte[] encode = new byte[password.Length];
encode = Encoding.UTF8.GetBytes(password);
strmsg = Convert.ToBase64String(encode);
return strmsg;
}
如果你在数据库中存储密码,除非你有很好的理由需要能够获得纯文本,否则你应该散列你的密码,而不是将它们加密或纯文本存储。
加密和散列之间的区别在于,加密可以检索纯文本,而散列不能。当您存储密码时,您应该使用用户提供的密码并对其进行散列(理想情况下使用盐),然后当用户下次尝试使用该密码登录时,您再次对其进行散列,然后将存储的散列与您刚刚生成的散列进行比较,如果它们匹配则它们是相同的。
我在这里写过这个(密码存储,如何正确使用),并有更完整的解释。
我有几个哈希函数可用在我的网站上的代码(在VB。. NET,但它们很容易移动到c#),可能最好的是使用SHA512(计算字符串或文件的SHA512散列)。
如果你仍然不确定哈希等,请随意说出你不理解的地方,我会尽力帮助:)