Python和Java AES / ECB / PKCS5加密

时间:2018-08-30 05:33:47

标签: java python encryption

JAVA版本:

public class EncryptUtil {
    public static String AESEncode(String encodeRules, String content) {
        try {
            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            keygen.init(128, new SecureRandom(encodeRules.getBytes()));
        SecretKey original_key = keygen.generateKey();
        byte[] raw = original_key.getEncoded();
        SecretKey key = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] byte_encode = content.getBytes("utf-8");
        byte[] byte_AES = cipher.doFinal(byte_encode);
        return new String(Base64.getEncoder().encode(byte_AES));
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
       return null;
   }

}

当我运行此代码时:

System.out.println(EncryptUtil.AESEncode("1234567812345678", python&java"));

我有:

V5FFUgDi7VZaJ0qGzDISoA==

PYTHON版本:

import base64

from Crypto.Cipher import AES

BLOCK_SIZE = 16  # Bytes
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * \
            chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
unpad = lambda s: s[:-ord(s[len(s) - 1:])]


class AESUtil:
    __BLOCK_SIZE_16 = BLOCK_SIZE_16 = AES.block_size

    def __init__(self, key):
         self.key = key

    def encrypt(self, raw):
        raw = pad(raw)
        cipher = AES.new(self.key, AES.MODE_ECB)
        return base64.b64encode(cipher.encrypt(raw))

    def decrypt(self, enc):
        enc = base64.b64decode(enc)
        cipher = AES.new(self.key, AES.MODE_ECB)
        return unpad(cipher.decrypt(enc))

我知道Java默认使用AES / ECB / PKCS#5,但是当我运行encrypt方法时:

cipher_text = AESUtil("1234567812345678").encryt('python&java')

得到:b'3mjygpK1d7ThCRK98ssZhA=='

我在Googles中找到了便笺簿和便笺簿。 如何编辑我的PYTHON代码,使cipher_text等于JAVA加密。 有人知道如何解决吗?

1 个答案:

答案 0 :(得分:0)

您使用其他加密密钥

在Java中

  

System.out.println(EncryptUtil.AESEncode(“ 1234567812345678”,“ python&java”));

查看代码:

KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128, new SecureRandom(encodeRules.getBytes()));
SecretKey original_key = keygen.generateKey();
byte[] raw = original_key.getEncoded();

如果您打印raw密钥,则会得到fd839759956ba4a47922e8ee7c902f52(十六进制编码),这就是加密密钥

如果您想直接使用提供的密钥,则应使用

byte[] raw = encodeRules.getBytes(); 
// (assuming encodeRules has 16 bytes)
  

如何编辑我的PYTHON代码,使cipher_text等于JAVA加密

这很棘手..您可能会看到how SecureRandom works,但是恕我直言,修复Java实现以创建您期望的键更容易

尽管我认为实施还不够安全-使用ECB和简单密钥。