尝试解密时,“要解密的数据长度无效”错误

时间:2015-10-20 11:27:26

标签: c# encryption

我正在尝试解密存储在Asp.Net Identity“密码”中的密码。我这样做,但得到错误“要解密的数据长度无效”。密码存储为“1000:salt:password”。

public string DecryptPassword(string hashedPassword)
{
    char[] delimiter = { ':' };
    string[] split = hashedPassword.Split(delimiter);
    //get byte representation of string          
    byte[] hash = Convert.FromBase64String(split[2]);
    byte[] salt = new byte[SIZE_OF_SECRETKEY];
    Rfc2898DeriveBytes pwdGen = new Rfc2898DeriveBytes(hash, salt, 1000);
    RijndaelManaged _RijndaelManaged = new RijndaelManaged();
    _RijndaelManaged.BlockSize = 256;
    byte[] key = pwdGen.GetBytes(_RijndaelManaged.KeySize / 8);   //This will generate a 256 bits key
    byte[] iv = pwdGen.GetBytes(_RijndaelManaged.BlockSize / 8);  //This will generate a 256 bits IV
    _RijndaelManaged.Key = key;
    _RijndaelManaged.IV = iv;
    byte[] plainText2 = null;
    using (MemoryStream ms = new MemoryStream())
    {
        using (CryptoStream cs = new CryptoStream(ms, _RijndaelManaged.CreateDecryptor(), CryptoStreamMode.Write))
        {
            cs.Write(hash, 0, hash.Length);
        }
        plainText2 = ms.ToArray();
    }
    //Decrypted text
    return System.Text.Encoding.Unicode.GetString(plainText2);
}

使用此代码进行哈希:

HashPassword(string password)
{
    RNGCryptoServiceProvider csprng = new RNGCryptoServiceProvider();
    byte[] salt = new byte[SIZE_OF_SECRETKEY];
    csprng.GetBytes(salt);

    // Hash the password and encode the parameters
    byte[] hash = PBKDF2(password, salt, ITERATIONS, HASH_SIZE);
    return ITERATIONS + ":" + Convert.ToBase64String(salt) + ":" + Convert.ToBase64String(hash);
}

1 个答案:

答案 0 :(得分:1)

无法从ASP.NET身份表中解密密码。

这些密码经过哈希处理,未加密。

哈希是一种单向操作,你不能将它反转为它的纯文本等价物。

加密密码是双向操作,您可以在加密和解密表示之间前后移动(假设您有密钥)。