基于此: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
吗?
答案 0 :(得分:2)
不,你不应该使用SHA256,SHA256是一个散列函数,其中Rfc2898DeriveBytes
用于实现基于密码的密钥派生功能。
哈希函数可用于验证数据,其中Rfc2898DeriveBytes
专门用于生成密钥。
通过msdn Rfc2898DeriveBytes 和SHA256