You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java AES加密逻辑迁移至Python的输出匹配问题求解

  • 免责声明:本次迁移涉及的加密方式不安全,是我接手的遗留系统,所有相关人员均知晓该情况,本次操作是下线该存在更多严重问题的遗留系统的第一步。

我现有一套Java语言实现的AES加密系统,计划将其迁移至Python实现,Java侧的加密代码如下:

public static String encrypt(String text, SecretKey secretKey) throws Exception {
    byte[] cipherText = null;
    String encryptedString = null;

    // get an RSA cipher object and print the provider
    Cipher cipher = Cipher.getInstance(SYMMETRIC_KEY_ALGORITHM); // AES

    // encrypt the plain text using the public key
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    cipherText = cipher.doFinal(text.getBytes());
    encryptedString = Base64.getEncoder().encodeToString(cipherText);

    return encryptedString;
}

我当前使用的是Python Cryptography库实现对应逻辑,已停止维护的PyCrypto库在我的Windows系统上无法安装,因此不采用该库方案。

我最初的实现代码如下,运行后可得到加密结果,但与Java侧输出不匹配:

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

key = b'Some random key '
cipher = Cipher(algorithms.AES(key), modes.GCM(b'000000000000'))
encryptor = cipher.encryptor()
ct = encryptor.update(ENC_MESSAGE)

base64EncodedStr = base64.b64encode(ct).decode('utf-8')
print('BASE64:', base64EncodedStr)

参照回答更新后的尝试:
我将加密模式从GCM改为ECB,此时Python输出与Java结果几乎一致,更新后的代码如下:

key = b'Some random key '

cipher = Cipher(algorithms.AES(key), modes.ECB())
encryptor = cipher.encryptor()
ct = encryptor.update(PLAINTEXT.encode('utf-8'))

base64EncodedStr = base64.b64encode(ct).decode('utf-8')
print('Encrypted:', base64EncodedStr)

Java侧参考输出长度为1004字符,Python输出长度为984字符,除Python输出末尾3个字符外,其余内容完全匹配;且经过解密验证,两者的加密结果解密后均可得到相同明文。

最终更新

经排查问题出在填充逻辑上,我调整代码添加了PKCS7填充后,Java与Python的加密输出完全一致,修复后的代码如下:

from cryptography.hazmat.primitives import padding as symmetric_padding

padder = symmetric_padding.PKCS7(algorithms.AES.block_size).padder()
padded_data = padder.update(PLAINTEXT.encode('utf-8')) + padder.finalize()

ct = encryptor.update(padded_data)

内容的提问来源于stack exchange,提问作者jwh20

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 19:54:03