我已经在互联网上搜索了一个多小时,只能找到我最新的扫描发现的客户端讨论。我收到的是使用 Read() 方法的方法,因为 Read() 忽略返回的值可能会导致程序忽略意外状态和条件查找。如果有人可以详细解释,并可能建议修复,那就太好了。函数如下:
方法中违规的代码行:
csEncrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
调用方法:
public String DecryptMessage(byte[] encrypted)
{
ASCIIEncoding textConverter = new ASCIIEncoding();
decryptor = aes.CreateDecryptor(key, IV);
MemoryStream msDecrypt = new MemoryStream(encrypted);
csEncrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
byte[] fromEncrypt = new byte[encrypted.Length];
csEncrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
return textConverter.GetString(fromEncrypt);
}
尽量不要忽略返回值:
public String DecryptMessage(byte[] encrypted)
{
ASCIIEncoding textConverter = new ASCIIEncoding();
decryptor = aes.CreateDecryptor(key, IV);
using (MemoryStream msDecrypt = new MemoryStream(encrypted))
{
using (var csEncrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
byte[] fromEncrypt = new byte[encrypted.Length];
var bytesRead = csEncrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
return textConverter.GetString(fromEncrypt, 0, bytesRead);
}
}
}
如果返回的字节数少于预期,代码中会发生什么情况?