aes.py
2.4 KB
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
#这个有问题
from Crypto.Cipher import AES
from base64 import b64encode, b64decode
def encrypt_ecb(data, key):
data = data.encode()
key = key.encode()
aes = AES.new(key, AES.MODE_CBC, bytes(16))
res = aes.encrypt(pad(data, 32))
return b64encode(res).decode()
def decrypt(data, key, iv):
key = key.encode()
iv = iv.encode()
# aes = AES.new(key, AES.MODE_CBC, bytes(16))
aes = AES.new(key, AES.MODE_CBC, iv)
res = aes.decrypt(b64decode(data))
return unpad(res, 32).decode()
def unpad(padded_data, block_size, style='pkcs7'):
pdata_len = len(padded_data)
if pdata_len == 0:
raise ValueError("Zero-length input cannot be unpadded")
if pdata_len % block_size:
raise ValueError("Input data is not padded")
if style in ('pkcs7', 'x923'):
padding_len = bord(padded_data[-1])
if padding_len<1 or padding_len>min(block_size, pdata_len):
raise ValueError("Padding is incorrect.")
if style == 'pkcs7':
if padded_data[-padding_len:]!=bchr(padding_len)*padding_len:
raise ValueError("PKCS#7 padding is incorrect.")
else:
if padded_data[-padding_len:-1]!=bchr(0)*(padding_len-1):
raise ValueError("ANSI X.923 padding is incorrect.")
elif style == 'iso7816':
padding_len = pdata_len - padded_data.rfind(bchr(128))
if padding_len<1 or padding_len>min(block_size, pdata_len):
raise ValueError("Padding is incorrect.")
if padding_len>1 and padded_data[1-padding_len:]!=bchr(0)*(padding_len-1):
raise ValueError("ISO 7816-4 padding is incorrect.")
else:
raise ValueError("Unknown padding style")
return padded_data[:-padding_len]
def pad(data_to_pad, block_size, style='pkcs7'):
padding_len = block_size-len(data_to_pad)%block_size
if style == 'pkcs7':
padding = bchr(padding_len)*padding_len
elif style == 'x923':
padding = bchr(0)*(padding_len-1) + bchr(padding_len)
elif style == 'iso7816':
padding = bchr(128) + bchr(0)*(padding_len-1)
else:
raise ValueError("Unknown padding style")
return data_to_pad + padding
def bord(s):
return s
def bchr(s):
return bytes([s])
if __name__ == '__main__':
decrypt_data = decrypt('QkjNiuixpmtcxxqxaIZ30A==', 'm0XsOHC52YZ5KtakhpuMSZtF7DhwudmG', 'OCRocr2024UATocr')
print('解密:', decrypt_data)