java - 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
我已经解决了几天,但看不出问题出在哪里。
解决方案
您有不同的代码结构,这使得比较示例变得困难。在您的 Python 代码中有 a message
,但在您的 Java 代码中没有。
我的第一个猜测是您应该调用digest
而不是hexdigest
在 Python 代码中调用。
https://docs.python.org/2/library/hashlib.html
您正在进行从哈希到字符串到二进制数据的转换,其中一些使用 UTF-8,但没有。我建议您打印并比较两种语言中传递给加密函数的实际值。
推荐阅读
- r - 以累积方式在数据框列表中建立一个值
- python-3.x - mimtproxy 运行 python 脚本:“XX 模块未导入”
- apache-spark - 使用 Windows env 在分布式集群上运行的 Spark 作业抱怨无法删除临时文件夹之一
- c# - 将字符串转换为 ReadOnlyMemory
在 C# 中? - azure-active-directory - Azure AD MFA 可以与本地 Active Directory 一起使用吗?
- reactjs - 何等待 fetch 直到 redux 状态可用?
- mysql - sql中的累计总数
- javascript - 如何多次调用一个函数,纯JS
- next.js - getStaticProps 是否在服务器上运行?
- javascript - 正在搜索产品代码,但代码中包含字母