crypt.py 1.0 KB

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