为什么AES解密会给出空结果?

2024-05-18 10:08:30 发布

您现在位置:Python中文网/ 问答频道 /正文

使用AES在java中进行加密,并希望用Python进行解密,但结果在Python中是空的(没有错误)。 请在标记为副本之前查看代码。我想检测代码中的问题。你知道吗

java加密代码:

public static String encrypt(String plainText)  throws Exception {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    keyGenerator.init(128);

    SecretKey secretKey = keyGenerator.generateKey();
    String keyStr = Base64.encodeToString(secretKey.getEncoded(), Base64.NO_WRAP);
    byte[] initVector = new byte[16];
    (new Random()).nextBytes(initVector);

    IvParameterSpec iv = new IvParameterSpec(initVector);
    SecretKeySpec skeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

    byte[] plainTextByte = plainText.getBytes();
    byte[] encryptedByte = cipher.doFinal(plainTextByte);
    byte[] messagebytes = new byte[initVector.length + encryptedByte.length];

    System.arraycopy(initVector, 0, messagebytes, 0, 16);
    System.arraycopy(encryptedByte, 0, messagebytes, 16, encryptedByte.length);

    return Base64.encodeToString(messagebytes, Base64.NO_WRAP);
}

Python代码

def decrypt(key, message):
    """
    Input encrypted bytes, return decrypted bytes, using iv and key
    """

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

    iv = byte_array[0:16] # extract the 16-byte initialization vector

    messagebytes = byte_array[16:] # encrypted message is the bit after the iv

    cipher = AES.new(key.encode("UTF-8"), AES.MODE_CBC, iv)

    decrypted_padded = cipher.decrypt(messagebytes)

    decrypted = unpad(decrypted_padded)

    return decrypted.decode("UTF-8");

Tags: 代码newstringbyteaescipherbase64secretkey
1条回答
网友
1楼 · 发布于 2024-05-18 10:08:30

我看到Java显式地将字符串编码为return Base64.encodeToString(messagebytes, Base64.NO_WRAP);处的基64

但是我看到您又在用python byte_array = message.encode("UTF-8")编码,在这里您必须对加密的消息进行解码

# Standard Base64 Decoding
decodedBytes = base64.b64decode(encodedStr)
decodedStr = str(decodedBytes, "utf-8")

然后才能解密解码的信息。你知道吗

相关问题 更多 >