python 中的 AES-128 CBC 加密

AES-128 CBC encryption in python

我正试图摆脱下面的 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 and 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 Encrypting with PyCrypto AES