使用Aes进行文件加密 [英] Using Aes for file encryption

查看:574
本文介绍了使用Aes进行文件加密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我没有使用太多加密,所以这可能是一个基本问题.我正在编写一个小程序,使用来自用户的username password 信息对文件进行加密.

目前,我已经创建了AesManaged 的实例,无论我是对数据进行加密还是解密,该实例总是以相同的方式实例化.

代码如下:

Hi,

I haven''t been using encryption much so this is probably a basic question. I''m writing a small program to encrypt a file using username and password information from the user.

Currently I''ve created an instance of AesManaged which is always instantiated the same way, regardless if I''m encrypting or decrypting the data.

The code is as follows:

private static System.Security.Cryptography.Aes InitAes(string username, string password) {
   System.Security.Cryptography.Aes aes = new System.Security.Cryptography.AesManaged();

   aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
   aes.KeySize = 128;
   aes.Key = System.Text.Encoding.Unicode.GetBytes(password);
   aes.IV = System.Text.Encoding.Unicode.GetBytes(username);

   return aes;
}


如您所见,我只是将密码用作密钥,将用户名用作IV.

现在,我已经了解到,在这种情况下,首选的方法是使用Rfc2898DeriveBytes生成密钥和IV.
我要问的问题:正确吗?如果是的话,我应该如何使用Rfc2898DeriveBytes?如果我在加密中使用随机盐,该如何解密文件?


As you can see I''ve simply used the password as key and the username as IV.

Now, I''ve understood that in this situation the preferred way is to generate both key and IV with Rfc2898DeriveBytes.

The question I''m asking: Is that correct? And if it is, how should I use Rfc2898DeriveBytes? If I use random salt in encryption, how should I decrypt the file?

推荐答案

不确定这是否是解决问题的最佳方法,但是我想出了以下解决方案.

  • 定义新的Rfc2898DeriveBytes
  • 将密码定义为Rfc2898DeriveBytes的密码(这很奇怪)
  • 将用户名定义为salt
  • 使用Aes
  • Key前16个字节(128位)用作初始化矢量
Not sure if this is the best approach for the question, but I came up with the following solution.

  • Define a new Rfc2898DeriveBytes
  • Define the password as the password for Rfc2898DeriveBytes (well this was surpising)
  • Define the username as salt
  • Use the first 16 bytes (128 bit) as the Key for Aes
  • Use the next 16 bytes as the initialization vector
private static System.Security.Cryptography.Aes InitAes(string username, string password) {
   System.Security.Cryptography.Aes aes = new System.Security.Cryptography.AesManaged();
   System.Security.Cryptography.Rfc2898DeriveBytes rfc2898 
   = new System.Security.Cryptography.Rfc2898DeriveBytes(password, 
                                                         System.Text.Encoding.Unicode.GetBytes(username));

   aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
   aes.KeySize = 128;
   aes.Key = rfc2898.GetBytes(16);
   aes.IV = rfc2898.GetBytes(16);

   return aes;
}



如果有人有评论或增强的想法,请随时将其添加为评论或解决方案.



If anybody has comments or enhancement ideas, feel free to add them as comments or solutions.


这篇关于使用Aes进行文件加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆