1234567891011121314151617181920212223242526 |
- from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
- from cryptography.hazmat.backends import default_backend
- class AESCipher:
- def __init__(self):
- self.key = b'50102fa64073ad76' # 用适当的方式转换或直接定义为字节串
- self.iv = b'173d023138824bb0' # 同上
- def aes_encrypt(self, data):
- cipher = Cipher(algorithms.AES(self.key), modes.CBC(self.iv), backend=default_backend())
- encryptor = cipher.encryptor()
- ct = encryptor.update(self._pad(data).encode()) + encryptor.finalize()
- return ct.hex().upper()
- def aes_decrypt(self, data):
- cipher = Cipher(algorithms.AES(self.key), modes.CBC(self.iv), backend=default_backend())
- decryptor = cipher.decryptor()
- decrypted_data = decryptor.update(bytes.fromhex(data)) + decryptor.finalize()
- return self._unpad(decrypted_data).decode()
- def _pad(self, s):
- return s + (16 - len(s) % 16) * chr(16 - len(s) % 16)
- def _unpad(self, s):
- return s[:-ord(s[len(s) - 1:])]
|