简体   繁体   中英

How do I encrypt in Python and decrypt in Java?

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.

I would strongly recommend using a cross-language crypto API for this. I am a big fan of Keyczar , and it just so happens to have Java and Python libraries. The API is about as simple as:

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

in both Java and Python .

  • Python 2 string literals like 'abc' and "abc" are ASCII.
  • Python 2 string literals like u'abc' and u"abc" are unicode.
  • Python 3 string literals like 'abc' and "abc" are unicode.
  • Python 3 string literals like b'abc' and b"abc" are a bytes type.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM