What symmetric encryption algorithms implemented in both of c# and php do not requires fixed lenght of input data?

StackOverflow https://stackoverflow.com/questions/16980987

Вопрос

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.

Это было полезно?

Решение

From my point of view you shouldn't hide the exception at that level. Throwing an exception when an user tries to decrypt an unencrypted piece of data seems the expected behavior of a cryptography module to me.

Instead, you should deal with this exception at a higher level (outside the cryptography module). For instance, you could have something like this in your UI layer:

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");
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top