#!/usr/bin/env python
# -*- coding: utf-8 -*-
import hashlib
from Crypto.Cipher import AES
import base64
from binascii import b2a_hex
def create_md5_pwd(password):
m = hashlib.md5()
b = password.encode(encoding='utf-8')
m.update(b)
md5_pwd = m.hexdigest()
return md5_pwd
class PrpCrypt(object):
def __init__(self, API_SECRET):
self.key = API_SECRET[:16].encode('gbk') # 密匙
self.iv = API_SECRET[16:].encode('gbk') # 密匙向量
def encrypt(self,text):
# 加密
mycipher = AES.new(self.key, AES.MODE_CBC, self.iv)
# 加密的明文长度必须为16的倍数,如果长度不为16的倍数,则需要补足为16的倍数
# 将iv(密钥向量)加到加密的密文开头,一起传输
ciphertext = self.iv + mycipher.encrypt(text.encode())
return ciphertext # 加密
def decrypt(self,text):
# 解密
mydecrypt = AES.new(self.key, AES.MODE_CBC, text[:16])
decrypttext = mydecrypt.decrypt(text[16:])
decrypt_pwd = decrypttext.decode() # 解密后数据
return decrypt_pwd
if __name__ == '__main__':
password = '密码11111111'
API_SECRET = "22222222222" # 点睛提供
text = create_md5_pwd(password)
pc = PrpCrypt(API_SECRET) # 初始化密匙
ciphertext = pc.encrypt(text)
e = b2a_hex(ciphertext)[32:].decode()
d = pc.decrypt(ciphertext)
print('加密后:' + e)
print('解密后:' + d)