【Py】使用PyCryptodome进行对称加密

123 篇文章 4 订阅
import json
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
from base64 import b64encode, b64decode

# 加密与解密所使用的密钥,长度必须是16的倍数
# 随机生成密钥
key = b64encode(get_random_bytes(16)).decode('utf-8')
#key = pad("ThisIs SecretKey2".encode('utf-8'), AES.block_size)
# 要加密的明文数据,长度必须是16的倍数
data = pad("Hello, World123!2".encode('utf-8'), AES.block_size)
# IV参数,长度必须是16, 如果不指定iv则会随机生成
#iv = 'This is an IV456'.encode('utf-8')

# 数据加密
cipher1 = AES.new(b64decode(key), AES.MODE_CBC)
cipher_data = cipher1.encrypt(data)
iv = b64encode(cipher1.iv).decode('utf-8')
ct = b64encode(cipher_data).decode('utf-8')
result = json.dumps({'key':key, 'iv':iv, 'ciphertext':ct})
print(result)

# 数据解密
b64 = json.loads(result)
key = b64decode(b64['key'])
iv = b64decode(b64['iv'])
ct = b64decode(b64['ciphertext'])
cipher2 = AES.new(key, AES.MODE_CBC, iv)
# 解密后的明文数据
pt = unpad(cipher2.decrypt(ct), AES.block_size)
print('The message was: ', pt.decode('utf-8'))

# {"key": "Xj52movZaYmw3YI8lFjeiA==", "iv": "wssYy7cavdYzpN89ZzaVOQ==", "ciphertext": "R/7dokPvS312p/JTRly1PSkOVlsfJYfkb+nJIrtXw4I="}
# The message was:  Hello, World123!2

以上代码中,如果不在加密前对明文以及密钥pad,则如果长度不是16的倍数会报错。通过pad会将明文及密钥长度填充至16的倍数,通过unpad会将pad填充的内容去掉,恢复至原来的长度。

参考:
https://www.cnblogs.com/yyds/p/7072492.html
https://pycryptodome.readthedocs.io/en/latest/src/util/util.html
https://pycryptodome.readthedocs.io/en/latest/src/cipher/classic.html#cbc-mode
https://blog.csdn.net/bandaoyu/article/details/105552003

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值