【问题标题】:AES Encryption in c#c#中的AES加密
【发布时间】:2016-05-24 14:21:28
【问题描述】:

我尝试使用示例 MSDN https://msdn.microsoft.com/ru-ru/library/system.security.cryptography.aes(v=vs.110).aspx 加密文件 当我加密一个 .txt 文件时,一切都很好,但是当我尝试加密其他文件(.bmp、.pdf ...)时,文件没有被解密。 哪里出错了?

我修改了下载文件的代码

internal static void EncryptAes(string pathData, string pathEnCrypt)
    {
        string plainText;
        using (StreamReader sr = new StreamReader(pathData))
            plainText = sr.ReadToEnd();
        byte[] encrypted;
        // Create an Aes object
        // with the specified key and IV.
        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;

            // Create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {

                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
            using (FileStream fstream = new FileStream(pathEnCrypt, FileMode.Create))
                fstream.Write(encrypted, 0, encrypted.Length);
        }
    }

【问题讨论】:

  • "当我尝试加密其他文件(.bmp、.pdf ...)时,文件没有被解密。"您的意思是“那么文件未加密”吗?还是真的是后面的解密失败了?
  • 它是加密的,因为它是奇怪的,文件大小增加了一半。然后就可以解密了,但是打开还是不行
  • 你可以尝试只使用 BinaryReader 和 BinaryWriter(不是 StreamReader 和 StreamWriter),因为 bmp 等是二进制文件...
  • 注释和代码不匹配:decrytorCreateEncryptor// Create a decrytor to perform the stream transform. ICryptoTransform encryptor = aesAlg.CreateEncryptor(((aesAlg.Key, aesAlg.IV);
  • 这可能对你有帮助:stackoverflow.com/questions/4816121/…

标签: c# encryption aes


【解决方案1】:

StreamReader 应该使用特定编码的文本数据。因此,您不能将其用于二进制数据。

如果文件不大,您可以将文件内容读入MemmoryStream,然后将其用于AES。

【讨论】:

    【解决方案2】:

    像处理字符串一样处理十六进制/二进制数据会导致数据丢失,因此您将无法完全恢复它。要了解/更多想法,您可能需要查看this,它解释了您想为 VB.NET 做什么

    【讨论】:

      猜你喜欢
      • 2013-07-25
      • 1970-01-01
      • 2013-04-19
      • 1970-01-01
      • 2012-12-22
      • 2012-11-13
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多