重用ICryptoTransform对象

时间:2017-04-24 16:37:14

标签: c# cryptography cryptostream .net-4.6.2

我有一个用于加密文本数据的类。我试图尽可能重用ICryptoTransform对象。但是,第二次尝试使用同一个对象时,我得到部分错误的解密数据。我认为第一个块是错误的,但其余的似乎没问题(用较长的文本测试它)。

我把课程拆了下来:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Sample.Crypto
{
    public class EncryptedStreamResolver : IDisposable
    {
        private AesCryptoServiceProvider _cryptoProvider;
        private ICryptoTransform _encryptorTransform;
        private ICryptoTransform _decryptorTransform;

        private ICryptoTransform EncryptorTransform
        {
            get
            {
                if (null == _encryptorTransform || !_encryptorTransform.CanReuseTransform)
                {
                    _encryptorTransform?.Dispose();
                    _encryptorTransform = _cryptoProvider.CreateEncryptor();
                }
                return _encryptorTransform;
            }
        }

        private ICryptoTransform DecryptorTransform
        {
            get
            {
                if (null == _decryptorTransform || !_decryptorTransform.CanReuseTransform)
                {
                    _decryptorTransform?.Dispose();
                    _decryptorTransform = _cryptoProvider.CreateDecryptor();
                }
                return _decryptorTransform;
            }
        }

        public EncryptedStreamResolver()
        {
            GenerateCryptoProvider();
        }

        public Stream OpenRead(string rawPath)
        {
            return new CryptoStream(File.OpenRead(rawPath + ".crypto"), DecryptorTransform, CryptoStreamMode.Read);
        }

        public Stream OpenWrite(string rawPath)
        {
            return new CryptoStream(File.OpenWrite(rawPath + ".crypto"), EncryptorTransform, CryptoStreamMode.Write);
        }

        private void GenerateCryptoProvider(string password = "totallysafepassword")
        {
            _cryptoProvider = new AesCryptoServiceProvider();
            _cryptoProvider.BlockSize = _cryptoProvider.LegalBlockSizes.Select(ks => ks.MaxSize).Max();
            _cryptoProvider.KeySize = _cryptoProvider.LegalKeySizes.Select(ks => ks.MaxSize).Max();
            _cryptoProvider.IV = new byte[_cryptoProvider.BlockSize / 8];
            _cryptoProvider.Key = new byte[_cryptoProvider.KeySize / 8];

            var pwBytes = Encoding.UTF8.GetBytes(password);
            for (var i = 0; i < _cryptoProvider.IV.Length; i++)
                _cryptoProvider.IV[i] = pwBytes[i % pwBytes.Length];
            for (var i = 0; i < _cryptoProvider.Key.Length; i++)
                _cryptoProvider.Key[i] = pwBytes[i % pwBytes.Length];
        }

        public void Dispose()
        {
            _encryptorTransform?.Dispose();
            _decryptorTransform?.Dispose();
            _cryptoProvider?.Dispose();
        }
    }
}

我已经编写了一个示例用法测试来演示问题:

public void Can_reuse_encryptor()
{
    const string message = "Secret corporate information here.";
    const string testFilePath1 = "Foo1.xml";
    const string testFilePath2 = "Foo2.xml";
    var sr = new EncryptedStreamResolver();

    // Write secret data to file
    using (var writer = new StreamWriter(sr.OpenWrite(testFilePath1)))
        writer.Write(message);

    // Read it back and compare with original message
    using (var reader = new StreamReader(sr.OpenRead(testFilePath1)))
        if (!message.Equals(reader.ReadToEnd()))
            throw new Exception("This should never happend :(");

    // Write the same data again to a different file
    using (var writer = new StreamWriter(sr.OpenWrite(testFilePath2)))
        writer.Write(message);

    // Read that back and compare
    using (var reader = new StreamReader(sr.OpenRead(testFilePath2)))
        if (!message.Equals(reader.ReadToEnd()))
            throw new Exception("This should never happend :(");
}

我错过了什么?文档表明这些对象是可重用的,但我无法理解。有人能帮帮我吗?

修改

正如@bartonjs指出的那样,如果我将包含上述代码的项目重新定位到.NET 4.6(或更高版本),我可以像这样使用 System.AppContext.TryGetSwitch

var reuseTransform = false;
if (null == _decryptorTransform ||
    !(AppContext.TryGetSwitch("Switch.System.Security.Cryptography.AesCryptoServiceProvider.DontCorrectlyResetDecryptor", out reuseTransform) && reuseTransform && _decryptorTransform.CanReuseTransform))
{
    _decryptorTransform?.Dispose();
    _decryptorTransform = _cryptoProvider.Createdecryptor();
}

然后我可以在主应用程序的app.config中设置此开关,如@ bartonjs&#39;答案。

1 个答案:

答案 0 :(得分:4)

您缺少的是.NET Framework中的错误(和错误修复):)。

关于同样的问题有一个Microsoft Connect Issue;特别是AesCryptoServiceProvider.CreateDecryptor()返回一个说CanReuseTransform=true的对象,但似乎行为不正确。

该错误已在.NET 4.6.2版本中修复,但在retargeting change后面被保护。这意味着,为了看到您需要的修复

  1. 安装.NET Framework 4.6.2或更高版本。
  2. 将主可执行文件的最低框架版本更改为4.6.2或更高版本。
  3. 如果您安装了较新的框架,但希望将可执行文件定位到较低版本的框架,则需要将切换Switch.System.Security.Cryptography.AesCryptoServiceProvider.DontCorrectlyResetDecryptor设置为false

    来自AppContext class documentation(在“备注”下):

      

    一旦定义并记录了交换机,调用者就可以通过使用注册表,将AppContextSwitchOverrides元素添加到其应用程序配置文件中,或通过编程方式调用AppContext.SetSwitch(String, Boolean)方法来使用它。

    对于配置文件(your.exe.config):

    <configuration>
      <runtime>
        <AppContextSwitchOverrides
          value="Switch.System.Security.Cryptography.AesCryptoServiceProvider.DontCorrectlyResetDecryptor=false" />
      </runtime>
    </configuration>