使用Sha256或Rfc2898DeriveBytes创建IC

时间:2012-09-28 12:45:56

标签: c# encryption sha256

基于此:http://www.superstarcoders.com/blogs/posts/symmetric-encryption-in-c-sharp.aspx

我编写了字节数组的加密/解密:

public static byte[] EncryptFile(string password, byte[] bytes, string salt)
    {
        using (RijndaelManaged aesEncryption = new RijndaelManaged())
        {
            DeriveBytes rgb = new Rfc2898DeriveBytes(password, Encoding.Unicode.GetBytes(salt));
            byte[] rgbKey = rgb.GetBytes(aesEncryption.KeySize >> 3);
            byte[] rgbIV = rgb.GetBytes(aesEncryption.BlockSize >> 3);
            aesEncryption.KeySize = 256;
            aesEncryption.Mode = CipherMode.CBC;
            aesEncryption.Padding = PaddingMode.PKCS7;
            aesEncryption.IV = rgbIV;
            aesEncryption.Key = rgbKey;
            using (ICryptoTransform crypto = aesEncryption.CreateEncryptor())
            {
                return crypto.TransformFinalBlock(bytes, 0, bytes.Length);
            }
        }
    }

    public static byte[] DecryptFile(string password, byte[] bytes, string salt)
    {
        using (RijndaelManaged aesEncryption = new RijndaelManaged())
        {
            DeriveBytes rgb = new Rfc2898DeriveBytes(password, Encoding.Unicode.GetBytes(salt));
            byte[] rgbKey = rgb.GetBytes(aesEncryption.KeySize >> 3);
            byte[] rgbIV = rgb.GetBytes(aesEncryption.BlockSize >> 3);
            aesEncryption.KeySize = 256;
            aesEncryption.Mode = CipherMode.CBC;
            aesEncryption.Padding = PaddingMode.PKCS7;
            aesEncryption.IV = rgbIV;
            aesEncryption.Key = rgbKey;
            using (ICryptoTransform crypto = aesEncryption.CreateDecryptor())
            {
                return crypto.TransformFinalBlock(bytes, 0, bytes.Length);
            }
        }
    }

但是在计算IV和密钥时,我应该使用SHA256代替Rfc2898DeriveBytes吗?

1 个答案:

答案 0 :(得分:2)

不,你不应该使用SHA256,SHA256是一个散列函数,其中Rfc2898DeriveBytes用于实现基于密码的密钥派生功能。

哈希函数可用于验证数据,其中Rfc2898DeriveBytes专门用于生成密钥。

通过msdn Rfc2898DeriveBytes SHA256