How to encrypt in Python and decrypt in Java?

I am trying to encrypt some data in a Python program and save it, and then decrypt this data in a Java program. In Python, I encrypt 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 decrypt 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 . It’s clear that I am doing something wrong. But what?

+7
source share
3 answers

The reason you have a problem is because the security policy limits the size of your key to 128 bits and you try to use a 256-bit key (Java Cryptography Extension (JCE) Unlimited Strength protection policy files are needed).

Check out this discussion and you will probably notice that 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. In addition, I think you should make the following change to c.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(new byte[16])); You are missing an initialization vector for CFB mode. If the decrypted value is incorrect, check the key initialization method.

+6
source

I would highly recommend Use the cross-language cryptographic API for this. I am a big fan of Keyczar , and it so happens that it has Java and Python libraries. The API is about as simple as:

 public String encrypt(String data) public String decrypt(String data) 

in Java and Python .

+4
source
  • Python 2 string literals such as "abc" and "abc" are ASCII.
  • Python string literals such as u'abc 'and u "abc" are unicode.
  • Python 3 string literals such as "abc" and "abc" are unicode.
  • Python 3 string literals, such as b'abc 'and b "abc", are byte types.

Java uses unicode by default, similar to Python 3.

For cross-language interoperable cryptography, you can check https://code.google.com/p/keyczar/ . There are simple examples of its use on this page.

+1
source

All Articles