python写的AES128/ECB/pkcs7加密解密函数

因为需要,要实现一个python版的AES128加解密方法,加密模式ECB,填充模式pkcs7.(貌似pkcs5和pkcs7是一模一样的,我没有看具体原因(好像是aes没有64位的,64位对应5?))

下面直接贴源代码啦(我找了好几个东拼西凑出来的,反正能工作,也支持中文)

# -*- coding: utf-8 -*-
from Crypto.Cipher import AES
import os
 
BS = AES.block_size
pad =lambda s: s +(BS - len(s)% BS)* chr(BS - len(s)% BS)
unpad =lambda s : s[0:-ord(s[-1])]
 
key = os.urandom(16)# the length can be (16, 24, 32)
#key='xxxxx'#32位或者0-f的数值,对应16字节
text ='content==顶你哦,记得回访哦xxxxx'
 
cipher = AES.new(key, AES.MODE_ECB)#ECB模式 
 
encrypted = cipher.encrypt(pad(text)).encode('hex')
print encrypted  # will be something like 'f456a6b0e54e35f2711a9fa078a76d16'
 
decrypted = unpad(cipher.decrypt(encrypted.decode('hex')))
print decrypted  # will be 'to be encrypted'

原文链接:https://blog.csdn.net/jinking01/article/details/80542640

你可能感兴趣的:(python,python)