首页 > 解决方案 > 解密加密的密码

问题描述

在我的项目中,我有 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;
    }

我知道我可以将密码与盐进行比较,然后查看哈希是否相同,但如果我没记错的话,我也可以以某种方式解密加密密码。

任何帮助,将不胜感激。

标签: c#asp.net-corehashcryptography

解决方案


正如@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.
    }

推荐阅读