首页 > 解决方案 > AES加密不同的结果Java和Python

问题描述

我有这个 android java AES 加密代码来制作我的令牌,现在我也想在 python 中制作它,但是它有一些不同的结果。

爪哇

private Void encrypt(String password) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, ShortBufferException, BadPaddingException, IllegalBlockSizeException {

    byte[] bytes = password.getBytes(StandardCharsets.UTF_8);

    SecretKeySpec secretKeySpec = new SecretKeySpec(MessageDigest.getInstance("MD5")
    .digest("mysecretkey".getBytes(StandardCharsets.UTF_8)), "AES");

    Cipher instance = Cipher.getInstance("AES/ECB/PKCS5Padding");
    instance.init(1, secretKeySpec);

    byte[] bArr = new byte[instance.getOutputSize(bytes.length)];

    instance.doFinal(bArr, instance.update(bytes,0,bytes.length, bArr, 0));


    for (byte b : bArr){

        Log.d("encrypt", String.valueOf(b));

    }
}

Python

from Crypto.Cipher import AES

import hashlib


def pad(byte_array):
    BLOCK_SIZE = 16
    pad_len = BLOCK_SIZE - len(byte_array) % BLOCK_SIZE
    return byte_array + (bytes([pad_len]) * pad_len)


def encrypt(key, message):


    byte_array = message.encode("UTF-8")
    panjang = len(message)

    padded = pad(byte_array)

    cipher = AES.new(key.encode("UTF-8"), AES.MODE_ECB)
    encrypted = cipher.encrypt(padded)

    for b in encrypted:
        print(b)





password = "mypassword"

secret_key = "mysecretkey"
hashkey = hashlib.md5(secret_key.encode()).hexdigest()

encrypt(hashkey,password)

java结果

-25 -16 84 -36 100 -102 74 -98 -91 -77 100 -96 -86 28 -47 -67

蟒蛇结果

220 127 95 142 45 102 9 79 170 82 165 2 63 39 196 7

我已经解决了几天,但看不出问题出在哪里。

标签: javapythonandroidencryptionaes

解决方案


您有不同的代码结构,这使得比较示例变得困难。在您的 Python 代码中有 a message,但在您的 Java 代码中没有。

我的第一个猜测是您应该调用digest而不是hexdigest在 Python 代码中调用。 https://docs.python.org/2/library/hashlib.html

您正在进行从哈希到字符串到二进制数据的转换,其中一些使用 UTF-8,但没有。我建议您打印并比较两种语言中传递给加密函数的实际值。


推荐阅读