AES的加解密-python样例程序

本文详细介绍了在Python中使用`Crypto`库实现AES加密(CBC模式)和解密的过程,包括密钥和初始化向量的生成,以及消息填充和去除的函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Protocol.KDF import PBKDF2


def generate_key_and_iv(password, salt, key_size=32, iv_size=16):
    key_iv = PBKDF2(password, salt, dkLen=key_size + iv_size, count=100000)
    return key_iv[:key_size], key_iv[key_size:]


def encrypt_AES_CBC(message, password):
    salt = get_random_bytes(16)
    key, iv = generate_key_and_iv(password, salt)

    cipher = AES.new(key, AES.MODE_CBC, iv)
    #ciphertext = cipher.encrypt(pad(message.encode('utf-8'), [①]))
    ciphertext = cipher.encrypt(pad(message.encode('utf-8'), AES.block_size))
    return salt + ciphertext

def decrypt_AES_CBC(ciphertext, password):
    salt = ciphertext[:16]
    #ciphertext = ciphertext[②]
    ciphertext = ciphertext[16:]
    key, iv = generate_key_and_iv(password, salt)

    cipher = AES.new(key, AES.MODE_CBC, iv)
    decrypted_message = unpad(cipher.decrypt(ciphertext), AES.block_size)
    return decrypted_message.decode('utf-8')

def pad(message, block_size):
    #padding_size = block_size - len(message) % [③]
    padding_size = block_size - len(message) % block_size
    padding = bytes([padding_size] * padding_size)
    return message + padding

def unpad(padded_message, block_size):
    #padding_size = [④]
    padding_size = padded_message[-1]
    if padding_size < 1 or padding_size > block_size:
        raise ValueError("Invalid padding")
    if padded_message[-padding_size:] != bytes([padding_size] * padding_size):
        raise ValueError("Invalid padding")
    return padded_message[:-padding_size]

if __name__ == "__main__":
    # 要加密的消息和密码
    message = "Hello, this is a message to be encrypted using AES!"
    password = "1234456"

    # 加密46
    encrypted_data = encrypt_AES_CBC(message, password)
    print("Encrypted:", encrypted_data)

    # 解密
    decrypted_message = decrypt_AES_CBC(encrypted_data, password)
    print("Decrypted:", decrypted_message)
### 使用 OpenSSL 实现 AES-256-ECB 的加密和解密 #### 密钥与初始化向量 (IV) AES 是一种分组密码算法,支持多种操作模式。对于 ECB 模式而言,不需要使用 IV(初始向量)。然而,在实际应用中推荐使用带有随机 IV 的 CBC 或 GCM 等更安全的操作模式来替代 ECB。 当采用 AES-256 时,意味着使用的密钥长度为 256 位即 32 字节[^2]。需要注意的是 MCRYPT_RIJNDAEL_256 并不代表 AES-256;前者指的是 Rijndael 算法的一个变种,其区块大小为 256 位而不是标准的 128 位。 #### Python 中实现 AES-256-ECB 加密解密 下面给出一段简单的 Python 代码用于演示如何利用 `pycryptodome` 库执行 AES-256-ECB 方式的加解密: ```python from Crypto.Cipher import AES import base64 def pad(text): while len(text) % 16 != 0: text += b' ' return text key = b'Sixteen byte key' data_to_encrypt = 'This is a secret message.' cipher = AES.new(pad(key)[:32], AES.MODE_ECB) encrypted_data = cipher.encrypt(pad(data_to_encrypt.encode())) print(f"Encrypted Data: {base64.b64encode(encrypted_data)}") decipher = AES.new(pad(key)[:32], AES.MODE_ECB) decrypted_data = decipher.decrypt(encrypted_data).rstrip(b' ') print(f"Decrypted Text: {decrypted_data.decode()}") ``` 上述子展示了基本流程,但在生产环境中应当注意以下几点: - 不要硬编码敏感信息如密钥; - 对于字符串类型的明文应先转换成字节数组再处理; - 填充方式的选择取决于具体需求以及通信双方约定。 #### 安全提示 尽管这里提供了关于 AES-256-ECB 的说明及程序,但建议尽可能避免选用 ECB 模式因为该模式下相同的数据块会被映射到相同的密文上从而暴露出潜在的安全风险。相较之下,CBC、CTR 和 GCM 更适合大多数应用场景并能提供更好的安全性保障[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值