版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
采用AES对称加密算法
pip install pycrypto
key字节串,在对称密码中使用的密钥,密钥key 长度必须为16(AES-128), 24(AES-192),或者32 (AES-256)Bytes 长度
mode用于加密或解密的链接模式,默认为MODE_ECB
block_size, 加密它以前缀为密文
因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题,所以这里统一把加密后的字符串转化为16进制字符串
解密后,去掉补足的空格用strip() 去掉
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
class Crypt(object):
def __init__(self):
self.key = 'eCcGFZQj6PNoSSma31LR39rTzTbLkU8E'.encode('utf-8')
self.mode = AES.MODE_CBC
def encrypt(self, text):
count = len(text)
if count % 16 != 0:
add = 16 - (count % 16)
text = text + ('\0' * add)
cryptor = AES.new(self.key, self.mode, b'&y3dmpx-8sgnu%y+')
self.ciphertext = cryptor.encrypt(text.encode('utf-8'))
return b2a_hex(self.ciphertext).decode(encoding='utf-8')
def decrypt(self, text):
cryptor = AES.new(self.key, self.mode, b'&y3dmpx-8sgnu%y+')
plain_text = cryptor.decrypt(a2b_hex(text))
return plain_text.decode().rstrip('\0')
if __name__ == '__main__':
pc = Crypt() #初始化密钥
e = pc.encrypt('123456') #加密
d = pc.decrypt(e) #解密
print("加密:",str(e))
print("解密:",str(d))