加解密封装

加密、解密封装。包含AES加解密和MD5加密

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import base64
import hashlib
from Crypto.Cipher import AES as _AES
from cryptography.hazmat.primitives import padding

# 密钥
AES_KEY = base64.b64decode("bG9uZ2dlPTY2NmxvdmUhIQ==").decode() # 请修改 一定是 16位的字符串
# 偏移量
AES_IV = base64.b64decode("bG9uZ2dlPTg4OGxvdmUhIQ==").decode()
# 加盐
AES_SALT = base64.b64decode("bG9uZ2dlPTk5OWxvdmUhIQ==").decode()

# 处理AES加密和解密,(AES+CBC+pkcs7padding)
class AESCrypt():

def __init__(self):
self.IV = AES_IV.encode("utf-8")
self.KEY = AES_KEY.encode("utf-8")
self.SALT = AES_SALT.encode("utf-8")

def pkcs7_padding(self, data, block_size=128):
"""
密码必须满足8的倍数所以需要补位,PKCS7Padding用'\n'补位
:param data:
:param block_size:
:return:
"""
if not isinstance(data, bytes):
data = data.encode('utf-8')
padder = padding.PKCS7(block_size).padder()
return padder.update(data) + padder.finalize()

def generateKey(self):
"""
key加盐
:return:
"""
return hashlib.pbkdf2_hmac(hash_name="sha1", password=self.KEY, salt=self.SALT, iterations=1,
dklen=16)

def aes_encrypt(self, password: str):
"""
aes加密
:param password:
:return:
"""
key = self.generateKey()
padded_data = self.pkcs7_padding(password)
cipher = _AES.new(key, _AES.MODE_CBC, self.IV)
return base64.b64encode(cipher.encrypt(padded_data)).decode()

def aes_decrypt(self, content: str):
"""
aes解密
:param content:
:return:
"""
key = self.generateKey()
cipher = _AES.new(key, _AES.MODE_CBC, self.IV)
content = base64.b64decode(content)
return (cipher.decrypt(content).decode('utf-8')).replace('\n', '')


# 处理md5加密,未加盐
class MD5Crypt():
def md5_encrypt(self, content):
# 创建对象
md = hashlib.md5(content.encode('utf-8'))
return md.hexdigest()


if __name__ == '__main__':
ace = AESCrypt()
md5 = MD5Crypt()
enc_data = ace.aes_encrypt("123456")
print("加密:>>>>>{}".format(enc_data))
dec_data = ace.aes_decrypt(enc_data)
print("解码:>>>>>{}".format(dec_data))
c = md5.md5_encrypt("123456")
print(c)
------------- End -------------