-1

我已经在互联网上搜索了一个多小时,只能找到我最新的扫描结果的客户端讨论。我收到的是使用 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);
    }
4

1 回答 1

0

尽量不要忽略返回值:

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);
        }
    }
}

如果返回的字节数少于您的预期,您的代码会发生什么情况?

于 2015-06-11T20:38:44.003 回答