1
| pip install pycryptodome
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad import base64
key = b'1234567890abcdef' iv = b'abcdef1234567890' plain_text = '你好,世界!'
plain_bytes = pad(plain_text.encode('utf-8'), AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv) cipher_bytes = cipher.encrypt(plain_bytes)
cipher_b64 = base64.b64encode(cipher_bytes).decode('utf-8') print('加密后(base64):', cipher_b64)
cipher = AES.new(key, AES.MODE_CBC, iv) decrypted = unpad(cipher.decrypt(base64.b64decode(cipher_b64)), AES.block_size) print('解密后:', decrypted.decode('utf-8'))
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| from Crypto.Cipher import AES from Crypto.Util.Padding import pad
def aes_encrypt(data_string): key = "fd6b639dbcff0c2a1b03b389ec763c4b" iv = "77b07a672d57d64c" aes = AES.new( key=key.encode('utf-8'), mode=AES.MODE_CBC, iv=iv.encode('utf-8') ) raw = pad(data_string.encode('utf-8'), 16) return aes.encrypt(raw)
encrypted_bytes = aes_encrypt("Hello World!") print('加密后(bytes):', encrypted_bytes)
|
与前面代码的区别:
- 密钥/IV直接utf-8编码:key和iv直接用utf-8编码,不是十六进制转字节
- 返回原始字节:直接返回加密后的字节,不做base64或hex编码
- 函数封装:便于复用
- 接口更简洁:只需传入明文字符串,返回加密字节
- 适用场景不同:适合密钥/IV本身就是utf-8字符串的情况
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad import binascii
key_hex = '1234567890abcdef1234567890abcdef' iv_hex = 'abcdef1234567890abcdef1234567890' plain_hex = '48656c6c6f20576f726c6421'
key = binascii.unhexlify(key_hex) iv = binascii.unhexlify(iv_hex) plain_bytes = binascii.unhexlify(plain_hex)
plain_padded = pad(plain_bytes, AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv) cipher_bytes = cipher.encrypt(plain_padded)
cipher_hex = binascii.hexlify(cipher_bytes).decode('utf-8') print('加密后(hex):', cipher_hex)
cipher = AES.new(key, AES.MODE_CBC, iv) decrypted = unpad(cipher.decrypt(binascii.unhexlify(cipher_hex)), AES.block_size) print('解密后(hex):', binascii.hexlify(decrypted).decode('utf-8')) print('解密后(text):', decrypted.decode('utf-8'))
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| from Crypto.Cipher import AES from Crypto.Util.Padding import pad import binascii
def aes_encrypt(data_string): key_string = "4E2918885FD98109869D14E0231A0BF4" key = binascii.a2b_hex(key_string) iv_string = "16B17E519DDD0CE5B79D7A63A4DD801C" iv = binascii.a2b_hex(iv_string) aes = AES.new( key=key, mode=AES.MODE_CBC, iv=iv ) raw = pad(data_string.encode('utf-8'), 16) aes_bytes = aes.encrypt(raw) return binascii.b2a_hex(aes_bytes).decode().upper()
encrypted = aes_encrypt("Hello World!") print('加密结果:', encrypted)
|
与前面代码的区别:
- 函数封装:将加密逻辑封装成函数,便于复用
- API差异:使用
binascii.a2b_hex()
和 binascii.b2a_hex()
而非 unhexlify()/hexlify()
- 输出格式:结果转大写,更符合某些系统要求
- 固定密钥:密钥和IV硬编码在函数内,适合特定场景
- 简化接口:只需传入明文字符串,返回加密后的十六进制字符串
如果文章对你有帮助,欢迎点击上方按钮打赏作者,更多功能请访问博客站
AES加密的几种常用方式
https://blog.fxcxy.com/2025/05/26/AES加密的几种常用方式/