AES_CBC_PKCS7算法加解密Python实现

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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import base64

from Crypto.Cipher import AES
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import algorithms

'''
AES/CBC/PKCS7Padding 加密解密
环境需求:
pip3 install pycryptodome==3.9.0

'''


class PrpCrypt(object):

def __init__(self, key='0000000000000000'):
self.key = key.encode('utf-8')
self.mode = AES.MODE_CBC
self.iv = "98d71fe589499967".encode('utf-8') # b'0102030405060708'
# block_size 128位

# 加密函数,如果text不足16位就用空格补足为16位,
# 如果大于16但是不是16的倍数,那就补足为16的倍数。
def encrypt(self, text):
cryptor = AES.new(self.key, self.mode, self.iv)
text = text.encode('utf-8')

# 这里密钥key 长度必须为16(AES-128),24(AES-192),或者32 (AES-256)Bytes 长度
# 目前AES-128 足够目前使用

text = self.pkcs7_padding(text)
self.ciphertext = cryptor.encrypt(text)

# 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题
# 所以这里统一把加密后的字符串转化为base64字符
return str(base64.b64encode(self.ciphertext),'utf-8')

@staticmethod
def pkcs7_padding(data):
if not isinstance(data, bytes):
data = data.encode()

padder = padding.PKCS7(algorithms.AES.block_size).padder()

padded_data = padder.update(data) + padder.finalize()

return padded_data

@staticmethod
def pkcs7_unpadding(padded_data):
unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
data = unpadder.update(padded_data)
try:
uppadded_data = data + unpadder.finalize()
except ValueError:
raise Exception('无效的加密信息!')
else:
return uppadded_data

# 解密后,去掉补足的空格用strip() 去掉
def decrypt(self, text):
# 偏移量'iv'
cryptor = AES.new(self.key, self.mode, self.iv)
plain_text = cryptor.decrypt(base64.b64decode(text))

return bytes.decode(plain_text).rstrip("\x01"). \
rstrip("\x02").rstrip("\x03").rstrip("\x04").rstrip("\x05"). \
rstrip("\x06").rstrip("\x07").rstrip("\x08").rstrip("\x09"). \
rstrip("\x0a").rstrip("\x0b").rstrip("\x0c").rstrip("\x0d"). \
rstrip("\x0e").rstrip("\x0f").rstrip("\x10")


# 加解密
if __name__ == '__main__':
pc = PrpCrypt('7fb498553e3c462988c3b9573692bd5f') # 初始化密钥
a = "1654912813"
print("加密前:%s" % a)
b = pc.encrypt(a)
print("加密后:%s" % b)
data = """c6AN9oA6Gr8sb+zv5XB44GAoQ8rZaAVHdepoWQw+uQOD5I0751nnE6aoMjGvPw6Bgs2OhGZ
S9eqYOhzZoUUw3rw2RABCm2cRmhqx9DfqjTJ1gwe+CT1JxaZCVyI/Nv/Iv7HX/D9PiEp1vJx4mTIpVvAD/LlGkSvXsaF3Bhrx6xf0
1/5zTua7t4AKf3PYyhkFz/lgWUxCUHW/SgnYaBos9PqtJcX2TBWY31uOu+f759PAiuby65u1QEBuMkidTPgxzJI0ig9VBkuwtjJ//
XiRHcesOPJJhzTFzpyZF0fOo3gj7DaSt33GdQbqT46oXoObN32kyWyPwyQv6+wmqB2IgrWSWMrX2J/Ty351zgW88qB04IZx1JYH/b
lTBJtDekYJTW99wDWpxQ46UPW8IPtgYNjSz5NWdDbPdj0kOnzeCg4l3lyLkLu92aN/OBBApL44Ls8vYuu5GevhpwcoTZOJgTDwrIl
FgZN8amx0OD9AgPL98SOPx/2xLp2WJ9FpVN69Li++BBgb0xcHRmERIGpCSGXx2tmWKb5aXXCsBY66PI0iM0eQ2QfhCjPnd1g+8yzD
acCRJypXnfGRpWEMLP3lHNk07pHZniu3gsNo+wiB++JO6xISmo9R1GEFM999whGuDE5Av8zt95b+Pk/7Av0r9eFJ0zdZJX/AIEW4j
5qVCm6T2PUq1PtzTkXA8RVGMYrmc1edbhu6zHNXU4puYLShSeYrT1iDFoyA0MX3M05J3XO792heyS98R51N8TjKZs2VSQFkLFH3lK
diWmuGvwbZirTc4/ZN71V+1Jfic7UakLDguZ3HtBJhdxLgrK8NLnci0aEokoc/ax9t2qyAtcJYsU7UH9X6bNI95lhHCnx60+4HTVb
skjPtyvau2Zebi0FlocH4Nj+VCCt3atAT93Y0OrsI3xMg8nL2alWjwXVTXv0nh+o5nL/tOCyWUB3WdLb8wvgzIJGyIhpJNfzC7hyS
gO+CkxBLg8EyFf9h0kQS6Qwi9wTZSFsDhaFAE19UeCgyZbU0mlWXqBYHgwJ9Nw8gAo9LwoJ+u70Ch/GobBlSiBp4MzJjPpjmG9Gu7
+jiSaapm8DcFIkxRFTKxUNZs/dcIO63hbMLwajRVZJDboh1FYPZcN7SJ0mmRuS0so+X7XYHM+JidpQVm5wMSWZBIy0e670Zgm9plU
qcRaF03JDseRmkKwqpBrsbt11kPCZI4IFPw6M5sUT30ODzV87hNqIh/Jis0rXzRhp2PFkODlwdZigK9Bl5/CI4gWOJ+Ei1BNVLj1d
G9DjpNznmt99XsDAM7Dpl6+F4Glar6mo76zMHtm6UQ1u6vTOoy4a707BllO76Bx8xgFd1ETI9glhWAE68XXy8LHjBouLBcw2PV6oQ
ItSjTJ4ciX093F2eHpeX6/Hgxp7tTrtg3joWqKefpm+iCPKb4bCYhyLKIhh2BiSe/aABLWdwLZOezq1lGgnO5C7Qug8RMKbLodWyR
L3w0eTJQ7bx+LUth9kekEcXRjDjKVTShlJCauvg7BECrtSAXkHq8fayMvs7EvzzpcC39iVWqWlNDYaV1Q+mg2HHpk1tyyNbd6R+dN
6oo/0upaGvDLA7QvygqSn61vWNBYA0KG+mlnNTaOFcV7flX3rL38SaF+rZ48r+DkTin9jdtOQ2V2piFGxBvil4xIpzFPl3nyX/U6g
e1DOFdryHoj348wm1Cws="""
print(pc.decrypt(data))


AES_CBC_PKCS7算法加解密Python实现
https://kingjem.github.io/2022/06/11/AES-CBC-PKCS7算法加解密Python实现/
作者
Ruhai
发布于
2022年6月11日
许可协议