Reputation: 90201
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?
Upvotes: 8
Views: 9098
Reputation: 2804
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.
Upvotes: 6
Reputation: 2909
Java uses unicode by default, similar to Python 3.
For interlanguage, interoperable crypto, you might check out https://code.google.com/p/keyczar/ . There are simple examples of its use on that page.
Upvotes: 1