I need to decrypt an file in Java.
The file was encrypted in C# using RijndaelManaged.
This are the C# settings for the encryption (summarized and not mentioned are default value):
var crypto = new RijndaelManaged();
crypto.GenerateKey();
crypto.BlockSize = crypto.KeySize;
crypto.IV = crypto.Key;
crypto.Padding = PaddingMode.Zeros;
my java code so far, which produces an error:
java.security.InvalidAlgorithmParameterException: Wrong IV length: must be 16 bytes long
:
Key aesKey = new SecretKeySpec(key, "AES");
Cipher cipher2 = Cipher.getInstance("AES/CBC/noPadding");
byte[] iv = key;
IvParameterSpec ivspec = new IvParameterSpec(iv);
cipher2.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv));
byte[] decryptedFile = cipher2.doFinal(buildFile);
I see 2 Problems concerning the C# code:
- the generated Key is 256bit. Then the block size is set to to 256bit, but the standard is 128bit. As far as I know, Java is only able to use a 128bit block size, as the Error message suggests. At least I didn't find out how to set the block size.
- Rijndael uses
PaddingMode.Zeros
, whats the equivalent Padding for Cipher?
please be aware that I can't change the C# code
Is there even a way to decrypt this in Java?
Update - Solution
I finally managed to decrypt the file using BouncyCastle suggested by Topaco in the comments.
BouncyCastle includes RijndaelEngine
, same as the C# part. It allows to set the block size to 256bit.
To answer my 2. question: PaddinMode.Zeros
equals new ZeroBytePadding()
Full code:
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.engines.RijndaelEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.paddings.ZeroBytePadding;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
...
private byte[] decryptPart(byte[] part, byte[] key) throws Exception {
BlockCipher engine = new RijndaelEngine(key.length * 8);
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine),
new ZeroBytePadding());
KeyParameter keyParam = new KeyParameter(key);
CipherParameters cipherParams = new ParametersWithIV(keyParam, key);
cipher.init(false, cipherParams);
byte[] output = new byte[cipher.getOutputSize(part.length)];
int tam = cipher.processBytes(part, 0, part.length, output, 0);
try {
cipher.doFinal(output, tam);
} catch (Exception ce) {
ce.printStackTrace();
}
return output;
}