c# - 解密加密的密码
问题描述
在我的项目中,我有 Encrypt 方法和 Decrypt 方法。在一个小问题之后,很多文件都被删除了,我正在恢复它们。问题是解密方法已经消失了,我忘记了我从哪里得到的,哈哈。
这是 enc 方法:
public static string HashPassword(string password, string salt)
{
string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: password,
salt: Encoding.UTF8.GetBytes(salt),
prf: KeyDerivationPrf.HMACSHA1,
iterationCount: 10000,
numBytesRequested: 256 / 8));
return hashed;
}
我知道我可以将密码与盐进行比较,然后查看哈希是否相同,但如果我没记错的话,我也可以以某种方式解密加密密码。
任何帮助,将不胜感激。
解决方案
正如@EjoshuaS所说,您有点误会了,但话虽如此,我只是想向您展示如何使用存储在数据库中的哈希、盐和用户提供的密码来验证密码。它可能会帮助其他人。(我使用的是 HMACSHA512,但你可以使用 HMACSHA1)
private void CreatePasswordHash(string password)
{
byte[] passwordHash, passwordSalt;
using(var hmac = new System.Security.Cryptography.HMACSHA512()){
passwordSalt = hmac.Key;
passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
}
}
private bool VerifyPassword(string password, byte[] passwordHash, byte[] passwordSalt)
{
using(var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt)){
var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); // Create hash using password salt.
for (int i = 0; i < computedHash.Length; i++){ // Loop through the byte array
if(computedHash[i] != passwordHash[i]) return false; // if mismatch
}
}
return true; //if no mismatches.
}
推荐阅读
- pandas - 使用 pandas 准备行序列
- node.js - 使用无头浏览器的 Lambda 函数出现网络错误
- nginx - Can I use # "fragment" portion of URL in the Nginx Location matcher?
- nginx - nginx TLSv1.3 冗余握手后会话票?
- javascript - 包装器/父元素的填充无法按预期工作
- javascript - 使用 async/await 函数 node.js 获取“未定义”
- javascript - 弹出窗口总是显示相同的数据
- android - 为什么当我的应用程序关闭时我没有收到 FCM 通知?
- xml - 在 xquery 中根据输出是否格式正确使用 fn:parse-xml()
- kubernetes - Kubernetes 集群 v1.19.4 中处于待处理状态的 Coredns