AES的加解密-python样例程序

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值