Search code examples
c#encryptionbouncycastle

Force to decrypt file with wrong key - C# + Bouncy Castle


I'm writing a simple application where users can encrypt/decrypt files using one of the block algorithms like Rijndael. I have to encrypt the session key as well with the same algorithm and store it together with the cipher text in an xml file. The key used for session key encryption is a SHA256 hash of the user's password. The result is something like:

<File>
    <EncryptedKey>session key encrypted with user's password hash</EncryptedKey>
    <Data>Data encrypted with session key</Data>
</File>

While decrypting, user is asked to type the password, then the hash is generated and used as a key to decrypt EncryptedKey from xml file and then the session key can be used to decrypt the data.

It works when user types correct password, but I want the application to decrypt file even if the password is wrong. I'm using Bouncy Castle and now when password is wrong (so the session key is wrong either), it throws an Exception "Pad block corrupted". I don't want to display any message boxes informing that an error occurs. Instead, I want to decrypt the file anyway and just save garbage as a result. Is that possible? My code for decrypting:

IBufferedCipher cipher = CipherUtilities.GetCipher("Rijndael/ECB/PKCS7Padding");
KeyParameter par = new KeyParameter(generateHash(password));
cipher.Init(false, par);
byte[] output = cipher.DoFinal(data); // Exception here when password is wrong

I also tried to use ProcessBytes() method first and DoFinal() at the end, but it didn't work either.


Solution

  • That pretty well defies the point of encryption in the first place. Presumably you could catch the exception and, in your catch block, write junk data (maybe a Hex dump of the exception stack?) to a file- but why? As noted by Ramhound, that would give a malicious user data which could be used in a brute-force attack to compare with when they have successfully decrypted the file.

    I would go back to the assumptions/design phase of this: why do you want to avoid showing a message which states "The password provided did not match the expected password. Please re-enter. 3 Tries Remain." (or whatever)? What is gained by outputting a "junk" file?