m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

35 lines
996 B

6 months ago
  1. import pickle
  2. from Crypto.Cipher import AES
  3. from base64 import b64encode, b64decode
  4. __all__ = "encrypt", "decrypt"
  5. BLOCK_SIZE = 16
  6. INTERRUPT = b'\0' # something impossible to put in a string
  7. PADDING = b'\1'
  8. def pad(data):
  9. return data + INTERRUPT + PADDING * (BLOCK_SIZE - (len(data) + 1) % BLOCK_SIZE)
  10. def strip(data):
  11. return data.rstrip(PADDING).rstrip(INTERRUPT)
  12. def create_cipher(key, seed):
  13. if len(seed) != 16:
  14. raise ValueError("Choose a seed of 16 bytes")
  15. if len(key) != 32:
  16. raise ValueError("Choose a key of 32 bytes")
  17. return AES.new(key, AES.MODE_CBC, seed)
  18. def encrypt(plaintext_data, key, seed):
  19. plaintext_data = pickle.dumps(plaintext_data, pickle.HIGHEST_PROTOCOL) # whatever you give me I need to be able to restitute it
  20. return b64encode(create_cipher(key, seed).encrypt(pad(plaintext_data)))
  21. def decrypt(encrypted_data, key, seed):
  22. return pickle.loads(strip(create_cipher(key, seed).decrypt(b64decode(encrypted_data))))