Flutter端AES CTR加密后Python端解密失败问题求助
Flutter AES-CTR加密与Python解密适配问题解决
问题背景
前端用Flutter的AES-CTR模式加密文本,后端Python解密失败。Flutter端加密正常,但Python端解密结果为乱码。
Flutter加密代码
final plainText = "abcde";//encoded; final key = enc.Key.fromUtf8('12345678901234567890123456789012'); final iv = enc.IV.fromUtf8('12345'); final encrypter = enc.Encrypter(enc.AES(key, mode: enc.AESMode.ctr, padding: null)); final encrypted = encrypter.encrypt(plainText, iv: iv); print(encrypted.base64); // 输出: yJpzWuw=
原Python解密代码
print(text) # 输出: yJpzWuw= plaintext = text.encode('utf-8') key = '12345678901234567890123456789012'.encode("utf-8") iv = '12345'.encode('utf-8') iv_int = int.from_bytes(iv) aes = pyaes.AESModeOfOperationCTR(key, pyaes.Counter(iv_int)) decrypted = aes.decrypt(plaintext) print('Decrypted:', decrypted)
错误解密结果
Decrypted: b'\xe7:\xcb\x94\xbe\xbb\xf8\x1c'
解决方案
问题根源在于两处适配错误:
- 未对Base64编码的密文做解码,直接用字符串编码后的字节解密
- Flutter的
IV.fromUtf8('12345')会自动将IV补全至16字节(用0x00填充),而原Python代码未做补全,且字节转整数时未指定大端序
修改后的Python解密代码:
import base64 import pyaes ciphertext = base64.b64decode('yJpzWuw=') # 对Base64编码的密文解码 key = '12345678901234567890123456789012'.encode("utf-8") iv = '12345\0\0\0\0\0\0\0\0\0\0\0'.encode('utf-8') # 将IV补全为16字节,用0x00填充 iv_int = int.from_bytes(iv, 'big') # 按大端序将字节转为整数 aes = pyaes.AESModeOfOperationCTR(key, pyaes.Counter(iv_int)) decrypted = aes.decrypt(ciphertext) print('Decrypted:', decrypted)
内容的提问来源于stack exchange,提问作者Hansen
相关产品推荐
相关产品推荐

