Asp.net core 3.1 解密 CryptoStream 得到“输入数据不是一个完整的块”
Posted
技术标签:
【中文标题】Asp.net core 3.1 解密 CryptoStream 得到“输入数据不是一个完整的块”【英文标题】:Asp.net core 3.1 decrypting CryptoStream getting "The input data is not a complete block" 【发布时间】:2021-01-02 02:14:18 【问题描述】:我正在使用这篇博文尝试在 asp.net core 3.1 中进行加密和解密。 https://tudip.com/blog-post/how-to-securely-transfer-web-api-data-in-asp-net-core/
它展示了如何使用中间件加密和解密每个请求和响应
我要加密的 JSON 字符串是 = ""pageViews":37,"subscriberCount":2"
private static Aes GetEncryptionAlgorithm()
Aes aes = Aes.Create();
aes.Key = Convert.FromBase64String("73kczzrPtnn5GXxQtOI6m4AewK34F4IkT/yaeYZxr+M=");
aes.IV = Convert.FromBase64String("b8LAfmzY8WxGNrZeTye4hw==");
return aes;
private static CryptoStream EncryptStream(Stream responseStream)
Aes aes = GetEncryptionAlgorithm();
CryptoStream base64EncodedStream = new CryptoStream(responseStream, new ToBase64Transform(), CryptoStreamMode.Write);
CryptoStream cryptoStream = new CryptoStream(base64EncodedStream, aes.CreateEncryptor(aes.Key, aes.IV), CryptoStreamMode.Write);
return cryptoStream;
string responseBody = new StreamReader(memStream).ReadToEnd();
responseBody = "ueArUlJZD2e+KaC6I/fvp1GdG0lXAVWIXJ0MPkG9"; //加密字符串。
//尝试解密
private static Stream DecryptStream(Stream cipherStream)
Aes aes = GetEncryptionAlgorithm();
CryptoStream base64DecodedStream = new CryptoStream(cipherStream, new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces), CryptoStreamMode.Read);
CryptoStream decryptedStream = new CryptoStream(base64DecodedStream, aes.CreateDecryptor(aes.Key, aes.IV), CryptoStreamMode.Read);
return decryptedStream;
static async Task Main(string[] args)
string text2 = "ueArUlJZD2e+KaC6I/fvp1GdG0lXAVWIXJ0MPkG9";
MemoryStream ms = new MemoryStream();
var streamWriter = new StreamWriter(ms);
await streamWriter.WriteAsync(text2);
streamWriter.Flush();
ms.Position = 0;
var decypted = DecryptStream(ms);
StreamReader reader = new StreamReader(decypted);
string text = await reader.ReadToEndAsync();
Console.ReadLine();
//在reader.ReadToEndAsync()处出现异常“输入数据不是完整块”
还有一个问题 在客户端,我收到的加密字符串更短。
var httpResponseMessage = await httpclient.SendAsync(request, cancellationToken);
var test = await httpResponseMessage.Content.ReadAsStreamAsync();
StreamReader reader = new StreamReader(test);
string text = reader.ReadToEnd(); // encrypted response "ueArUlJZD2e+KaC6I/fvp1GdG0lXAVWIXJ0M"
客户端收到的加密数据比服务器加密字符串短。
服务器端加密字符串 = "ueArUlJZD2e+KaC6I/fvp1GdG0lXAVWIXJ0MPkG9"; 加密字符串客户端 = "ueArUlJZD2e+KaC6I/fvp1GdG0lXAVWIXJ0M"'
【问题讨论】:
【参考方案1】:在对 CryptoStream 对象调用 Write 方法后,必须始终调用 DisposeAsync。
【讨论】:
以上是关于Asp.net core 3.1 解密 CryptoStream 得到“输入数据不是一个完整的块”的主要内容,如果未能解决你的问题,请参考以下文章
ASP.NET Core--.net core 3.1 部署到 IIS
《ASP.NET Core 6框架揭秘》实例演示[19]:数据加解密与哈希
从 ASP.NET Core 3.1 升级到 ASP.NET 5.0 后,User.Claims 为空
Wcf 服务在 .NET Core 3.1 控制台应用程序中工作,但在 ASP.NET Core 3.1 Web API 中无法工作