python实现AES对称加密(AES模式为CBC,加密算法MCRYPT_RIJNDAEL_128)对MD5加密后的密码实现对称加密(点睛API)
1.对原始密码进行MD5加密:
def create_md5_pwd():
password = 'test'
m = hashlib.md5()
b = password.encode(encoding='utf-8')
m.update(b)
md5_pwd = m.hexdigest()
print(md5_pwd)
return md5_pwd
运行一下:
098f6bcd4621d373cade4e832627b4f6
2.使用AES对称加密来加密上面得到的MD5密码:
def encrypt():
text = '098f6bcd4621d373cade4e832627b4f6' # MD5加密所得
apiSecret = '12345678912345678912345678912345' # 点睛提供
# 加密
key = apiSecret[:16].encode('gbk')# 密匙,apiSecret的前十六位
iv = apiSecret[16:].encode('gbk')# 偏移量,apiSecret的后十六位
mycipher = AES.new(key, AES.MODE_CBC, iv)
# 加密的明文长度必须为16的倍数,如果长度不为16的倍数,则需要补足为16的倍数
# 将iv(密钥向量)加到加密的密文开头,一起传输
ciphertext = self.iv + mycipher.encrypt(text.encode())
e = b2a_hex(ciphertext)[32:].decode() # 加密后
print('加密后:' + e)
return ciphertext # 加密
运行一下:
加密后:21fa89586f4a299545307b99036a082e135b52d3f63f93541e4291669a0de1de
3.解密:
def decrypt():
# 解密
text = encrypt()
apiSecret = '12345678912345678912345678912345' # 点睛提供
key = apiSecret[:16].encode('gbk')# 密匙,apiSecret的前十六位
mydecrypt = AES.new(key, AES.MODE_CBC, text[:16])
decrypttext = mydecrypt.decrypt(text[16:])
decrypt_pwd = decrypttext.decode() # 解密后数据
print('解密后:' + decrypt_pwd)
return decrypt_pwd
运行下:
解密后:098f6bcd4621d373cade4e832627b4f6 #刚开始加密得到的MD5密码
4.完整代码:
#!/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 = 'test'
API_SECRET = "12345678912345678912345678912345" # 点睛提供
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)
运行结果:
加密后:21fa89586f4a299545307b99036a082e135b52d3f63f93541e4291669a0de1de
解密后:098f6bcd4621d373cade4e832627b4f6
大功告成,是不是很简单