2021-07-03 13:55:20 +08:00
|
|
|
import base64
|
|
|
|
import hashlib
|
|
|
|
|
|
|
|
from Crypto.Cipher import AES
|
2021-07-23 14:46:55 +08:00
|
|
|
|
2021-07-03 13:55:20 +08:00
|
|
|
from nonebot.utils import logger_wrapper
|
|
|
|
|
|
|
|
log = logger_wrapper("FEISHU")
|
|
|
|
|
2021-07-08 22:30:21 +08:00
|
|
|
|
2021-07-03 13:55:20 +08:00
|
|
|
class AESCipher(object):
|
|
|
|
def __init__(self, key):
|
|
|
|
self.block_size = AES.block_size
|
|
|
|
self.key = hashlib.sha256(AESCipher.str_to_bytes(key)).digest()
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def str_to_bytes(data):
|
2021-11-22 23:21:26 +08:00
|
|
|
u_type = type(b"".decode("utf8"))
|
2021-07-03 13:55:20 +08:00
|
|
|
if isinstance(data, u_type):
|
2021-11-22 23:21:26 +08:00
|
|
|
return data.encode("utf8")
|
2021-07-03 13:55:20 +08:00
|
|
|
return data
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _unpad(s):
|
2021-11-22 23:21:26 +08:00
|
|
|
return s[: -ord(s[len(s) - 1 :])]
|
2021-07-03 13:55:20 +08:00
|
|
|
|
|
|
|
def decrypt(self, enc):
|
2021-11-22 23:21:26 +08:00
|
|
|
iv = enc[: AES.block_size]
|
2021-07-03 13:55:20 +08:00
|
|
|
cipher = AES.new(self.key, AES.MODE_CBC, iv)
|
2021-11-22 23:21:26 +08:00
|
|
|
return self._unpad(cipher.decrypt(enc[AES.block_size :]))
|
2021-07-03 13:55:20 +08:00
|
|
|
|
|
|
|
def decrypt_string(self, enc):
|
|
|
|
enc = base64.b64decode(enc)
|
2021-11-22 23:21:26 +08:00
|
|
|
return self.decrypt(enc).decode("utf8")
|