1

Im using this code to decrypt AES data:

public static String decrypt(String ciphertext, String password)
{
    byte[] cipherdata = System.Convert.FromBase64String(ciphertext);

    byte[] iv = new byte[AESBlockSize * 4];
    Array.Copy(cipherdata, 0, iv, 0, iv.Length);

    byte[] input = new byte[cipherdata.Length - iv.Length];
    Array.Copy(cipherdata, iv.Length, input, 0, input.Length);

    Rfc2898DeriveBytes passwordDB = new Rfc2898DeriveBytes(password, iv, PBKDF2Iterations);
    byte[] keyBytes = passwordDB.GetBytes(256 / 8);

    RijndaelManaged symmetricKey = new RijndaelManaged();

    symmetricKey.Mode = CipherMode.CBC;
    symmetricKey.Padding = PaddingMode.ISO10126;

    ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, iv);

    MemoryStream memoryStream = new MemoryStream(input);
    CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);

    byte[] plainTextBytes = new byte[input.Length];

    int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);

    memoryStream.Close();
    cryptoStream.Close();

    return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}

I get the exception Padding is invalid and cannot be removed on the call to cryptoStream.Readwhen the wrong password is supplied.

Is there any way to prevent this exception when using the wrong password, because I'm trying to make a brute-forcer, and the exceptions are very slow to handle.

jbtule
  • 31,383
  • 12
  • 95
  • 128
Maestro
  • 9,046
  • 15
  • 83
  • 116
  • Your question might already have been answered [here](http://stackoverflow.com/q/11762/146622) and [here](http://stackoverflow.com/q/604210/146622), among others... – Daniel A.A. Pelsmaeker Apr 09 '13 at 11:16
  • 1
    Of course you can set the `PaddingMode` to none, but how will you test your password guess? – President James K. Polk Apr 09 '13 at 11:17
  • 1
    @Virtlink No it has not already been answered. Those people asks WHY they are getting the exception, I understand why, but want to know how I can prevent it. – Maestro Apr 09 '13 at 11:22
  • @GregS If its the correct password a known string will be in the output. – Maestro Apr 09 '13 at 11:22
  • Where is the encrypted data coming from? Are you sure you have all of it? See http://stackoverflow.com/questions/10469819/padding-is-invalid-and-cannot-be-removed-exception-while-decrypting-string-using – Adam Liss Apr 09 '13 at 12:01

1 Answers1

0

If you are just brute forcing go ahead and set the PaddingMode to None, you will decrypt the last block with the padding included, which you can use in your recognition of the plaintext with whatever else you are checking.

jbtule
  • 31,383
  • 12
  • 95
  • 128
  • Thanks, didnt realize it was so simple. It didn't make a big difference for performance, but it works. – Maestro Apr 09 '13 at 19:59