Python使用pycryptodome库来进行AES加密解密

一、安装pycryptodome库:

pip install pycryptodome

二、使用pycryptodome库:

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import hashlib

# 派生密钥函数
def get_key(password):
    hasher = hashlib.sha256()  # 生成32字节
    hasher.update(password)
    return hasher.digest()

# 加密函数
def encrypt_AES_GCM(msg, password):
    # 生成随机的nonce
    nonce = get_random_bytes(12)
    # 生成符合长度要求的密钥(密钥长度必须是16、24或者32字节)
    key = get_key(password)
    # 创建AES-GCM加密器
    cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
    # 加密消息
    ciphertext, tag = cipher.encrypt_and_digest(msg.encode('utf-8'))
    # 返回加密后的消息和nonce
    return (ciphertext, nonce, tag)

# 解密函数
def decrypt_AES_GCM(ciphertext, nonce, tag, password):
    # 生成符合长度要求的密钥
    key = get_key(password)
    # 创建AES-GCM解密器
    cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
    # 解密消息
    plaintext = cipher.decrypt_and_verify(ciphertext, tag)
    # 返回解密后的消息
    return plaintext.decode('utf-8')

# 测试加密解密
password = b'secret_password_123'
msg = 'Hello, world!'
ciphertext, nonce, tag = encrypt_AES_GCM(msg, password)
plaintext = decrypt_AES_GCM(ciphertext, nonce, tag, password)
print(plaintext)

运行结果: 

注意:在AES-GCM模式下,需要使用随机的nonce来保证加密的安全性。同时,需要使用tag来验证解密后的消息是否被篡改。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值