I'm trying to encrypt some data in a Python program and save it out, then decrypt that data in a Java program. In Python, I'm encrypting it like this:
from Crypto.Cipher import AES
KEY = '12345678901234567890123456789012'
def encrypt(data):
cipher = AES.new(KEY, AES.MODE_CFB)
return cipher.encrypt(data)
And in Java, I'm decrypting it like this:
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
public class Encryption {
private static byte[] KEY = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2' };
public static byte[] decrypt(byte[] data) throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher c = Cipher.getInstance("AES/CFB/NoPadding");
Key key = new SecretKeySpec(KEY, "AES");
c.init(Cipher.DECRYPT_MODE, key);
return c.doFinal(data);
}
}
But I get Exception in thread "main" java.security.InvalidKeyException: Illegal key size or default parameters
. Clearly, I'm doing something wrong. But what?
The reason you have a problem is because the security policy limits your key size to 128-bit and you are attempting to use a 256-bit key (need Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files).
Look at this discussion and you'll probably notice you have a similar problem. I actually had the same problem on my machine. After updating the security policy, I was able to run your code. Also, I think you should make the following change c.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(new byte[16]));
You are missing the initialization vector for the CFB mode. If the decrypted value is not correct, check the way you initialize the keys.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With