2012-09-28 39 views
0

:字节数组的http://www.superstarcoders.com/blogs/posts/symmetric-encryption-in-c-sharp.aspx使用SHA256或Rfc2898DeriveBytes在此基础上建立IC

我写的加密/解密:

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

所以你复制了一些随机码关闭互联网,并希望我们告诉你,如果它做正确的事? – dtb

+1

答案是否定的,顺便说一句。当您需要从密码派生密钥而不是SHA256时,应该使用Rfc2898DeriveBytes。 – dtb

回答

2

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

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

通过MSDN Rfc2898DeriveBytesSHA256