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

如何在PyCryptodome中使用这段PyCrypto风格的AES加密代码?

适配PyCryptodome的AES加密代码修改方案

嘿,我来帮你把这段原本适配PyCrypto的AES加密代码改成能在PyCryptodome环境中正常运行的版本。其实两者的API大部分是兼容的,但有几个关键细节需要调整,我会一步步给你说明:

核心修改点

  • 必须显式指定加密模式:PyCryptodome要求调用AES.new()时必须传入mode参数,原PyCrypto默认使用ECB模式(虽然ECB安全性极低,不推荐在实际项目中使用,但为了完全兼容你的原代码逻辑,我们暂时保留这个模式)。
  • 字符串与字节的转换:PyCryptodome的加密/解密方法只处理字节类型(bytes),而原代码直接传入字符串,所以需要显式用encode('utf-8')把字符串转成字节,解密后再用decode('utf-8')转回字符串。
  • Python版本兼容:原代码是Python2的写法(比如无括号的print语句),我们改成Python3兼容的函数形式。

修改后的完整代码

#!/usr/bin/env python3
from Crypto.Cipher import AES
import base64
import os

# 加密器对象的块大小;根据FIPS-197标准必须为16
BLOCK_SIZE = 16
# 填充使用的字符——对于AES这类块加密算法,待加密内容长度必须是BLOCK_SIZE的整数倍
# 该字符用于确保内容长度始终满足块大小要求
PADDING = '{'

# 用于为待加密文本填充至符合块大小要求的单行函数
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING

# 用于加密/编码和解密/解码字符串的单行函数
# 使用AES加密,再用base64编码
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s).encode('utf-8')))
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).decode('utf-8').rstrip(PADDING)

# 生成随机密钥
secret = os.urandom(BLOCK_SIZE)

# 使用随机密钥创建加密器对象,显式指定ECB模式(原PyCrypto默认模式)
cipher = AES.new(secret, AES.MODE_ECB)

# 加密字符串
encoded = EncodeAES(cipher, 'password')
print('Encrypted string:', encoded)

# 解密加密后的字符串
decoded = DecodeAES(cipher, encoded)
print('Decrypted string:', decoded)

额外建议:改用更安全的加密模式

ECB模式因为没有使用初始化向量(IV),相同的明文块会生成相同的密文块,非常容易被攻击。如果是实际项目使用,建议改用CBC模式(需要随机IV),这里给你一个参考示例:

#!/usr/bin/env python3
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import base64

BLOCK_SIZE = 16
PADDING = '{'
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING

# CBC模式需要将IV与密文一起保存,解密时复用
def EncodeAES_CBC(key, s):
    iv = get_random_bytes(BLOCK_SIZE)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    encrypted = cipher.encrypt(pad(s).encode('utf-8'))
    # 将IV和密文拼接后做base64编码,方便存储/传输
    return base64.b64encode(iv + encrypted)

def DecodeAES_CBC(key, e):
    data = base64.b64decode(e)
    iv = data[:BLOCK_SIZE]
    encrypted_content = data[BLOCK_SIZE:]
    cipher = AES.new(key, AES.MODE_CBC, iv)
    return cipher.decrypt(encrypted_content).decode('utf-8').rstrip(PADDING)

# 生成安全密钥
secret = get_random_bytes(BLOCK_SIZE)
# 加密
encoded = EncodeAES_CBC(secret, 'password')
print('Encrypted string (CBC):', encoded)
# 解密
decoded = DecodeAES_CBC(secret, encoded)
print('Decrypted string (CBC):', decoded)

内容的提问来源于stack exchange,提问作者S. Raud

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:14:17