AES.py 917 B

1234567891011121314151617181920212223242526272829303132333435
  1. from hashlib import sha256
  2. import base64
  3. from Crypto import Random
  4. from Crypto.Cipher import AES
  5. BS = 16
  6. pad = lambda s: bytes(s + (BS - len(s) % BS) * chr(BS - len(s) % BS), 'utf-8')
  7. unpad = lambda s : s[0:-ord(s[-1:])]
  8. class AESCipher:
  9. def __init__( self, key ):
  10. self.key = bytes(key, 'utf-8')
  11. def encrypt( self, raw ):
  12. raw = pad(raw)
  13. iv = Random.new().read( AES.block_size )
  14. print(iv,raw)
  15. cipher = AES.new(self.key, AES.MODE_CBC, iv )
  16. return (iv + cipher.encrypt( raw )).hex()
  17. def decrypt( self, enc ):
  18. enc = bytes.fromhex(enc)
  19. iv = enc[:16]
  20. print(iv,enc)
  21. cipher = AES.new(self.key, AES.MODE_CBC, iv )
  22. return unpad(cipher.decrypt( enc[16:] )).decode('utf8')
  23. cipher = AESCipher('mysecretpassword')
  24. encrypted = cipher.encrypt('Secret')
  25. decrypted = cipher.decrypt(encrypted)
  26. print(encrypted)
  27. print(decrypted)