Python AES加密

支持中文加密

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
import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES
class AESCipher(object):
def __init__(self, key):
self.bs = 32
self.key = hashlib.sha256(key.encode()).digest()
def encrypt(self, raw_msg):
key = self.key
iv = Random.new().read(AES.block_size)
msg = self._pad(raw_msg)
cipher = AES.new(key, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(msg))
def decrypt(self, encryptedData):
key = self.key
encryptedData = base64.b64decode(encryptedData)
iv = encryptedData[:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
return self._unpad(cipher.decrypt(encryptedData[AES.block_size:])).decode('utf-8')
def _unpad(self, s):
return s[:-ord(s[len(s)-1:])]
def _pad(self, s):
# new for chn 中文主要在原始串编码成utf8格式!
BS = self.bs
s = s.encode("utf-8")
return s + (BS - len(s) % BS) * chr(BS - len(s) % BS).encode("utf-8")
# 具体使用
key='中文key支持'
msg='具体需要加密的消息'
aes = AESCipher(key)
# 加密msg
msg_encrypted = aes.encrypt(msg)
# 解密msg
msg = aes.decrypt(msg_encrypted)