我正在使用与此处提供的字符串加密/解密类类似的字符串加密/解密类作为解决方案。
这在 .Net 5 中对我来说效果很好。
现在我想将我的项目更新到.Net 6。
使用 .Net 6 时,解密的字符串确实会根据输入字符串的长度被截断某个点。
▶️为了方便调试/重现我的问题,我创建了一个公共重现存储库here。
两者都使用完全相同的输入
"12345678901234567890"
以及路径短语 "nzv86ri4H2qYHqc&m6rL"
来调用加密方法。
.Net 5 输出:
"12345678901234567890"
"1234567890123456"
长度差异是
4
。
我还查看了 .Net 6 的重大更改,但找不到可以引导我找到解决方案的内容。
我很高兴就我的问题提出任何建议,谢谢!
加密类
public static class StringCipher
{
// This constant is used to determine the keysize of the encryption algorithm in bits.
// We divide this by 8 within the code below to get the equivalent number of bytes.
private const int Keysize = 128;
// This constant determines the number of iterations for the password bytes generation function.
private const int DerivationIterations = 1000;
public static string Encrypt(string plainText, string passPhrase)
{
// Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
// so that the same Salt and IV values can be used when decrypting.
var saltStringBytes = Generate128BitsOfRandomEntropy();
var ivStringBytes = Generate128BitsOfRandomEntropy();
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
using (var symmetricKey = Aes.Create())
{
symmetricKey.BlockSize = 128;
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
// Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
var cipherTextBytes = saltStringBytes;
cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
memoryStream.Close();
cryptoStream.Close();
return Convert.ToBase64String(cipherTextBytes);
}
}
}
}
}
}
public static string Decrypt(string cipherText, string passPhrase)
{
// Get the complete stream of bytes that represent:
// [32 bytes of Salt] + [16 bytes of IV] + [n bytes of CipherText]
var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
// Get the saltbytes by extracting the first 16 bytes from the supplied cipherText bytes.
var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
// Get the IV bytes by extracting the next 16 bytes from the supplied cipherText bytes.
var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
// Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();
using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
using (var symmetricKey = Aes.Create())
{
symmetricKey.BlockSize = 128;
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream(cipherTextBytes))
{
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);
}
}
}
}
}
}
private static byte[] Generate128BitsOfRandomEntropy()
{
var randomBytes = new byte[16]; // 16 Bytes will give us 128 bits.
using (var rngCsp = RandomNumberGenerator.Create())
{
// Fill the array with cryptographically secure random bytes.
rngCsp.GetBytes(randomBytes);
}
return randomBytes;
}
}
调用代码
var input = "12345678901234567890";
var inputLength = input.Length;
var inputBytes = Encoding.UTF8.GetBytes(input);
var encrypted = StringCipher.Encrypt(input, "nzv86ri4H2qYHqc&m6rL");
var output = StringCipher.Decrypt(encrypted, "nzv86ri4H2qYHqc&m6rL");
var outputLength = output.Length;
var outputBytes = Encoding.UTF8.GetBytes(output);
var lengthDiff = inputLength - outputLength;
原因是这个重大变化:
DeflateStream、GZipStream 和 CryptoStream 与典型的不同 Stream.Read 和 Stream.ReadAsync 行为有两种方式:
他们没有完成读取操作,直到缓冲区通过 到读操作被完全填满或流结束 已达到。
新行为是:
从 .NET 6 开始,当调用 Stream.Read 或 Stream.ReadAsync 时 受影响的流类型之一,其缓冲区长度为 N, 操作完成时:
至少已从流中读取一个字节,或底层 它们包装的流在对其读取的调用中返回 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);
}
您不会检查
Read
实际读取了多少字节以及是否全部读取了它们。在以前的 .NET 版本中,您可以避免这种情况,因为如上所述,CryptoStream
行为与其他流不同,而且您的缓冲区长度足以容纳所有数据。但是,情况不再是这样,您需要像检查其他流一样检查它。或者甚至更好 - 只需使用 CopyTo
:
using (var plainTextStream = new MemoryStream())
{
cryptoStream.CopyTo(plainTextStream);
var plainTextBytes = plainTextStream.ToArray();
return Encoding.UTF8.GetString(plainTextBytes, 0, plainTextBytes.Length);
}
或者甚至更好,正如另一个答案所建议的,因为你解密了 UTF8 文本:
using (var plainTextReader = new StreamReader(cryptoStream))
{
return plainTextReader.ReadToEnd();
}
我认为你的问题就在这里:
var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
Stream.Read
文档:
即使尚未到达流的末尾,实现也可以自由地返回比请求更少的字节。
因此,对
Read
的单次调用不能保证读取所有可用字节(最多 plainTextBytes.Length
)——它完全有权读取较少数量的字节。
.NET 6 有许多性能改进,如果这是他们以性能名义做出的权衡,我不会感到惊讶。
你必须保持良好状态,不断调用
Read
直到它返回 0
,这表明没有更多数据可返回。
但是,使用
StreamReader
会容易得多,它还会为您处理 UTF-8 解码。
return new StreamReader(cryptoStream).ReadToEnd();
我在我的 .net6 项目中使用了这 2 个扩展方法。
namespace WebApi.Utilities;
public static class StringUtil
{
static string key = "Mohammad-Komaei@Encrypt!keY#";
public static string Encrypt(this string text)
{
if (string.IsNullOrEmpty(key))
throw new ArgumentException("Key must have valid value.", nameof(key));
if (string.IsNullOrEmpty(text))
throw new ArgumentException("The text must have valid value.", nameof(text));
var buffer = Encoding.UTF8.GetBytes(text);
var hash = SHA512.Create();
var aesKey = new byte[24];
Buffer.BlockCopy(hash.ComputeHash(Encoding.UTF8.GetBytes(key)), 0, aesKey, 0, 24);
using (var aes = Aes.Create())
{
if (aes == null)
throw new ArgumentException("Parameter must not be null.", nameof(aes));
aes.Key = aesKey;
using (var encryptor = aes.CreateEncryptor(aes.Key, aes.IV))
using (var resultStream = new MemoryStream())
{
using (var aesStream = new CryptoStream(resultStream, encryptor, CryptoStreamMode.Write))
using (var plainStream = new MemoryStream(buffer))
{
plainStream.CopyTo(aesStream);
}
var result = resultStream.ToArray();
var combined = new byte[aes.IV.Length + result.Length];
Array.ConstrainedCopy(aes.IV, 0, combined, 0, aes.IV.Length);
Array.ConstrainedCopy(result, 0, combined, aes.IV.Length, result.Length);
return Convert.ToBase64String(combined);
}
}
}
public static string Decrypt(this string encryptedText)
{
if (string.IsNullOrEmpty(key))
throw new ArgumentException("Key must have valid value.", nameof(key));
if (string.IsNullOrEmpty(encryptedText))
throw new ArgumentException("The encrypted text must have valid value.", nameof(encryptedText));
var combined = Convert.FromBase64String(encryptedText);
var buffer = new byte[combined.Length];
var hash = SHA512.Create();
var aesKey = new byte[24];
Buffer.BlockCopy(hash.ComputeHash(Encoding.UTF8.GetBytes(key)), 0, aesKey, 0, 24);
using (var aes = Aes.Create())
{
if (aes == null)
throw new ArgumentException("Parameter must not be null.", nameof(aes));
aes.Key = aesKey;
var iv = new byte[aes.IV.Length];
var ciphertext = new byte[buffer.Length - iv.Length];
Array.ConstrainedCopy(combined, 0, iv, 0, iv.Length);
Array.ConstrainedCopy(combined, iv.Length, ciphertext, 0, ciphertext.Length);
aes.IV = iv;
using (var decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
using (var resultStream = new MemoryStream())
{
using (var aesStream = new CryptoStream(resultStream, decryptor, CryptoStreamMode.Write))
using (var plainStream = new MemoryStream(ciphertext))
{
plainStream.CopyTo(aesStream);
}
return Encoding.UTF8.GetString(resultStream.ToArray());
}
}
}
}
从 .net 2.2 升级到 6 后,我遇到了完全相同的问题。它不会读取整个缓冲区 - 大多数情况下仅读取最多 16 个字节,因此,只需在循环中将其分解到最多 16 个字节即可。
此代码可能有帮助:
int totalRead = 0;
int maxRead = 16;
while (totalRead < plainTextBytes.Length)
{
var countLeft = plainTextBytes.Length - totalRead;
var count = countLeft < 16 ? countLeft : maxRead;
int bytesRead = cryptoStream.Read(plainTextBytes, totalRead, count);
totalRead += bytesRead;
if (bytesRead == 0) break;
}
var decryptedByteCount = cryptoStream.ReadAtLeast(plainTextBytes, plainTextBytes.Length, false);
尝试使用
ReadAtLeast()