gpt4 book ai didi

C# 流读取器 ReadToEnd() 缺少最后一个字符

转载 作者:行者123 更新时间:2023-12-03 04:21:59 25 4
gpt4 key购买 nike

我正在尝试使用 AES 解密 C# 中的字符串:

public static string AesDecrypt(byte[] cipherText, byte[] Key, byte[] IV)
{
string plaintext = null;

// Create an Aes object with the specified key and IV
using Aes aesAlg = Aes.Create();
aesAlg.Padding = PaddingMode.Zeros;
aesAlg.Key = Key;
aesAlg.IV = IV;

// Create a decryptor to perform the stream transform
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

// Create the streams used for decryption
using MemoryStream msDecrypt = new MemoryStream(cipherText);
using CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
using StreamReader srDecrypt = new StreamReader(csDecrypt);

// Read the decrypted bytes from the decrypting stream and place them in a string
plaintext = srDecrypt.ReadToEnd();
return plaintext;
}

编码数据是 JSON,但是当我解密它时,我得到了所有正确的数据,除了 JSON 内容的结束 } 丢失。

我认为 AES 本身不是我的问题。我有疑问

plaintext = srDecrypt.ReadToEnd();

因为只缺少最后一个字符。

我不知道我是否应该显式刷新任何流,但无论如何,这是一个非常奇怪的问题。

这是加密的完整代码:

public static string AesEncrypt(string plainText, byte[] Key, byte[] IV)
{
// Create an Aes object with the specified key and IV
using Aes aesAlg = Aes.Create();
aesAlg.Padding = PaddingMode.Zeros;
aesAlg.Key = Key;
aesAlg.IV = IV;

// Create an encryptor 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);
swEncrypt.Flush();

return Convert.ToBase64String(msEncrypt.ToArray());
}

这就是我调用解密方法的方式:

public static AuthenticationData ParseAuthenticationToken(string token)
{
byte[] tokenBytes = Convert.FromBase64String(token);
string json = AesEncryption.AesDecrypt(tokenBytes, aes.Key, aes.IV);
return JsonConvert.DeserializeObject<AuthenticationData>(json);
}

最佳答案

问题出在您的加密代码中。尽管您正在调用 seEncrypt.Flush(),但您并未调用 csEncrypt.FlushFinalBlock()。当流被释放时,这种情况会自动发生,但直到调用 msEncrypt.ToArray() 后才执行此操作。我会将该代码重写为:

MemoryStream msEncrypt = new MemoryStream();
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using StreamWriter swEncrypt = new StreamWriter(csEncrypt);
swEncrypt.Write(plainText);
// swEncrypt is disposed here, flushing it. Then csEncrypt is disposed,
// flushing the final block.
}
return msEncrypt.ToArray();

关于C# 流读取器 ReadToEnd() 缺少最后一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59158471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com