rfc2898derivebytes decrypt in c#?

Viewed 25

I am trying to decrypt rfc2898derivebytes I am using RNGCryptoServiceProvider to generate sale and pass it to rfc2898derivebytes after generating the bytes i convert the bytes into string. Now i want to back the string but i don't know where i am doing mistake.

How do I decrypt the hashed value back to "string"?

These functions i am using to generate hash.

    private readonly int _hashSize = 32;
    private readonly int _hashIterations = 128;

    private byte[] CreateSalt()
    {
        byte[] salt;
        using (RNGCryptoServiceProvider rNGCryptoServiceProvider = new RNGCryptoServiceProvider())
        {
            rNGCryptoServiceProvider.GetBytes(salt = new byte[_hashSize]);
        }
        return salt;
    }

    private byte[] CreateHash(string input, byte[] salt)
    {
        byte[] hash;
        using (Rfc2898DeriveBytes hashGenerator = new Rfc2898DeriveBytes(input, salt, _hashIterations))
        {
            hash = hashGenerator.GetBytes(_hashSize);
        }
        return hash;
    }

    public HashDetail GenerateHash(string input)
    {
        if (string.IsNullOrEmpty(input))
            return null;
        byte[] salt = CreateSalt();
        byte[] hash = CreateHash(input, salt);

        return new HashDetail { Salt = Convert.ToBase64String(salt), HashedValue = Convert.ToBase64String(hash) };
       
    }

This function i am trying to decrytp the hash.

       public string GetPassword(string input,string salt)
       {
            Aes aesAlg = Aes.Create(); string plaintext = null; try
            {
            byte[] saltByte = Convert.FromBase64String(salt);
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(input, saltByte);
                aesAlg.BlockSize = aesAlg.LegalBlockSizes[0].MaxSize;
                aesAlg.KeySize = aesAlg.LegalKeySizes[0].MaxSize;
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);
            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                byte[] bytes = Convert.FromBase64String(hashedValue);
                using (MemoryStream msDecrypt = new MemoryStream(bytes))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                            plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
            finally
            {
                if (aesAlg != null) aesAlg.Clear();
            }
          return plaintext;
         }
0 Answers
Related