python中的AES-128 CBC加密



我正试图摆脱下面的openssl调用,并用纯python代码替换它。

import os

iv = "7bde5a0f3f39fd658efc45de143cbc94"
password = "3e83b13d99bf0de6c6bde5ac5ca4ae68"
msg = "this is a message"
out = os.popen(f'printf "{msg}" | openssl aes-128-cbc -base64 -K {password} -iv {iv}').read()
print(f"IV: {iv}")    
print(f"PWD: {password}")     
print(f"MSG: {msg}")   
print(f"OUT: {out}")   

收益率:

IV: 7bde5a0f3f39fd658efc45de143cbc94
PWD: 3e83b13d99bf0de6c6bde5ac5ca4ae68
MSG: this is a message
OUT: ukMTwxkz19qVPiwU8xa/YM9ENqklbZtB86AaVPULHLE=

在人们建议的3个不同的库和其他各种似乎不再有效的代码摘录之间,我无法可靠地在纯python中复制它。有人会有一个以上的工作代码示例吗?

使用Python3,您可以使用PyCryptodome、binascii和base64。

from base64 import b64encode, b64decode
from binascii import unhexlify
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
iv = "7bde5a0f3f39fd658efc45de143cbc94"
password = "3e83b13d99bf0de6c6bde5ac5ca4ae68"
msg = "this is a message"
print(f"IV: {iv}")
print(f"PWD: {password}")
print(f"MSG: {msg}")
# Convert Hex String to Binary
iv = unhexlify(iv)
password = unhexlify(password)
# Pad to AES Block Size
msg = pad(msg.encode(), AES.block_size)
# Encipher Text
cipher = AES.new(password, AES.MODE_CBC, iv)
cipher_text = cipher.encrypt(msg)
# Encode Cipher_text as Base 64 and decode to String
out = b64encode(cipher_text).decode('utf-8')
print(f"OUT: {out}")
# Decipher cipher text
decipher = AES.new(password, AES.MODE_CBC, iv)
# UnPad Based on AES Block Size
plaintext = unpad(decipher.decrypt(b64decode(out)), AES.block_size).decode('utf-8')
print(f'PT: {plaintext}')

你可以看到更多:

  1. Python中的AES-128 CBC解密
  2. 用PyCrypto-AES进行Python加密

相关内容

  • 没有找到相关文章

最新更新