更新到 .Net 6 时出现问题 - 加密字符串

Opt*_*tim 47 .net c# migration encryption .net-6.0

我正在使用与此处提供的类似的字符串加密/解密类作为解决方案。

\n

这在 .Net 5 中对我来说效果很好。
\n现在我想将我的项目更新到 .Net 6。

\n

使用 .Net 6 时,解密的字符串确实会根据输入字符串的长度在某个点被截断。

\n

\xe2\x96\xb6\xef\xb8\x8f 为了方便调试/重现我的问题,我在这里创建了一个公共重现存储库。

\n
    \n
  • 加密代码是标准 2.0 项目中特意使用的。
  • \n
  • 引用此项目的是 .Net 6 和 .Net 5 Console 项目。
  • \n
\n

两者都使用完全相同的输入"12345678901234567890"和路径短语调用加密方法"nzv86ri4H2qYHqc&m6rL"

\n

.Net 5 输出:"12345678901234567890"
\n.Net 6 输出:"1234567890123456"

\n

长度之差为4.

\n

我还查看了.Net 6 的重大更改,但找不到可以指导我找到解决方案的内容。

\n

我很高兴就我的问题提出任何建议,谢谢!

\n

加密等级

\n
public static class StringCipher\n{\n    // This constant is used to determine the keysize of the encryption algorithm in bits.\n    // We divide this by 8 within the code below to get the equivalent number of bytes.\n    private const int Keysize = 128;\n\n    // This constant determines the number of iterations for the password bytes generation function.\n    private const int DerivationIterations = 1000;\n\n    public static string Encrypt(string plainText, string passPhrase)\n    {\n        // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text\n        // so that the same Salt and IV values can be used when decrypting.  \n        var saltStringBytes = Generate128BitsOfRandomEntropy();\n        var ivStringBytes = Generate128BitsOfRandomEntropy();\n        var plainTextBytes = Encoding.UTF8.GetBytes(plainText);\n        using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))\n        {\n            var keyBytes = password.GetBytes(Keysize / 8);\n            using (var symmetricKey = Aes.Create())\n            {\n                symmetricKey.BlockSize = 128;\n                symmetricKey.Mode = CipherMode.CBC;\n                symmetricKey.Padding = PaddingMode.PKCS7;\n                using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))\n                {\n                    using (var memoryStream = new MemoryStream())\n                    {\n                        using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))\n                        {\n                            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);\n                            cryptoStream.FlushFinalBlock();\n                            // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.\n                            var cipherTextBytes = saltStringBytes;\n                            cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();\n                            cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();\n                            memoryStream.Close();\n                            cryptoStream.Close();\n                            return Convert.ToBase64String(cipherTextBytes);\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    public static string Decrypt(string cipherText, string passPhrase)\n    {\n        // Get the complete stream of bytes that represent:\n        // [32 bytes of Salt] + [16 bytes of IV] + [n bytes of CipherText]\n        var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);\n        // Get the saltbytes by extracting the first 16 bytes from the supplied cipherText bytes.\n        var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();\n        // Get the IV bytes by extracting the next 16 bytes from the supplied cipherText bytes.\n        var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();\n        // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.\n        var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();\n\n        using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))\n        {\n            var keyBytes = password.GetBytes(Keysize / 8);\n            using (var symmetricKey = Aes.Create())\n            {\n                symmetricKey.BlockSize = 128;\n                symmetricKey.Mode = CipherMode.CBC;\n                symmetricKey.Padding = PaddingMode.PKCS7;\n                using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))\n                {\n                    using (var memoryStream = new MemoryStream(cipherTextBytes))\n                    {\n                        using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))\n                        {\n                            var plainTextBytes = new byte[cipherTextBytes.Length];\n                            var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);\n                            memoryStream.Close();\n                            cryptoStream.Close();\n                            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    private static byte[] Generate128BitsOfRandomEntropy()\n    {\n        var randomBytes = new byte[16]; // 16 Bytes will give us 128 bits.\n        using (var rngCsp = RandomNumberGenerator.Create())\n        {\n            // Fill the array with cryptographically secure random bytes.\n            rngCsp.GetBytes(randomBytes);\n        }\n        return randomBytes;\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

调用代码

\n
var input = "12345678901234567890";\nvar inputLength = input.Length;\nvar inputBytes = Encoding.UTF8.GetBytes(input);\n\nvar encrypted = StringCipher.Encrypt(input, "nzv86ri4H2qYHqc&m6rL");\n\nvar output = StringCipher.Decrypt(encrypted, "nzv86ri4H2qYHqc&m6rL");\nvar outputLength = output.Length;\nvar outputBytes = Encoding.UTF8.GetBytes(output);\n\nvar lengthDiff = inputLength - outputLength;\n
Run Code Online (Sandbox Code Playgroud)\n

Evk*_*Evk 66

原因是这个重大变化

DeflateStream、GZipStream 和 CryptoStream 在两个方面与典型的 Stream.Read 和 Stream.ReadAsync 行为不同:

直到传递给读取操作的缓冲区完全填满或到达流末尾时,它们才完成读取操作。

新的行为是:

从 .NET 6 开始,当对具有长度为 N 的缓冲区的受影响流类型之一调用 Stream.Read 或 Stream.ReadAsync 时,操作将在以下情况下完成:

至少已从流中读取了一个字节,或者它们包装的底层流从对其读取的调用中返回 0,表示没有更多数据可用。

在您的情况下,您会因为Decrypt方法中的以下代码而受到影响:

using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
    var plainTextBytes = new byte[cipherTextBytes.Length];
    var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
    memoryStream.Close();
    cryptoStream.Close();
    return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
Run Code Online (Sandbox Code Playgroud)

您不检查实际读取了多少字节Read以及是否读取了全部字节。在以前的 .NET 版本中,您可以避免这种情况,因为如上所述,CryptoStream行为与其他流不同,而且您的缓冲区长度足以容纳所有数据。但是,情况不再是这样,您需要像检查其他流一样检查它。或者甚至更好 - 只需使用CopyTo

using (var plainTextStream = new MemoryStream())
{
    cryptoStream.CopyTo(plainTextStream);
    var plainTextBytes = plainTextStream.ToArray();
    return Encoding.UTF8.GetString(plainTextBytes, 0, plainTextBytes.Length);
} 
Run Code Online (Sandbox Code Playgroud)

或者甚至更好,正如另一个答案所建议的那样,因为您解密了 UTF8 文本:

using (var plainTextReader = new StreamReader(cryptoStream))
{
    return plainTextReader.ReadToEnd();
}  
Run Code Online (Sandbox Code Playgroud)

  • `CopyTo`救了我,谢谢! (4认同)
  • 感谢您的解释。今天它让我摆脱了很多麻烦。 (2认同)

can*_*on7 23

认为你的问题出在这里:

var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
Run Code Online (Sandbox Code Playgroud)

来自Stream.Read文档

即使尚未到达流的末尾,实现也可以自由地返回比请求更少的字节。

因此,单次调用Read不能保证读取所有可用字节(最多plainTextBytes.Length)——读取较少数量的字节完全在其权限之内。

.NET 6 有许多性能改进,如果这是他们以性能名义做出的权衡,我不会感到惊讶。

您必须保持良好状态,并继续调用Read直到返回0,这表明没有更多数据可返回。

但是,使用 a 会容易得多StreamReader,它还会为您处理 UTF-8 解码。

return new StreamReader(cryptoStream).ReadToEnd();
Run Code Online (Sandbox Code Playgroud)