0

Currently I use AES and have a problem, if user choose to decode unencrypted file, my prog always ends up with exception, even when try catch placed and running out of debugger.

public static byte[] AES_Decrypt(byte[] data, string[] aes_key)
{
    RijndaelManaged aes = new RijndaelManaged();
    aes.KeySize = 256;
    aes.BlockSize = 256;
    aes.Mode = CipherMode.CBC;
    aes.Padding = PaddingMode.PKCS7;

    aes.Key = Encoding.Default.GetBytes(aes_key[0]);
    aes.IV = Encoding.Default.GetBytes(aes_key[1]);

    if (data.Length % (aes.BlockSize / 8) != 0)
        return null;

    var decrypt = aes.CreateDecryptor();

    using (MemoryStream ms = new MemoryStream())
    {
        using (CryptoStream cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write))
            try { cs.Write(data, 0, data.Length); } //crash here "data lenght for decryption is invalid" and "Padding is invalid and cannot be removed".
            catch (Exception exc) { return null; }

        return ms.ToArray();
    }
}

I am not that interested why try and catch don't work, I need some workaround to avoid crash... And changing the encryption method is fine.

4

1 回答 1

1

从我的角度来看,您不应该在该级别隐藏异常。当用户尝试解密未加密的数据时抛出异常对我来说似乎是加密模块的预期行为。

相反,您应该在更高级别(在密码学模块之外)处理此异常。例如,你可以在你的 UI 层有这样的东西:

try
{
    var encryptedFilePath = ShowOpenFileDialog();
    var decryptedFilePath = TryDecryptFile(encryptedFilePath);
    ShowMessagePopup("Your file has been decrypted to: " + decryptedFilePath);
}
catch (CryptographicException)
{
    ShowErrorPopup("Unable to decrypt file!\n" +
     "Please make sure the file you selected is valid");
}
于 2013-06-07T13:06:18.370 回答