0

基于此: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 而不是 SHA256Rfc2898DeriveBytes吗?

4

1 回答 1

2

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

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

通过 msdn Rfc2898DeriveBytesSHA256

于 2012-09-28T12:51:28.600 回答