fork download
  1. import base64
  2. import hashlib
  3. from Crypto import Random
  4. from Crypto.Cipher import AES
  5.  
  6. class AESCipher(object):
  7.  
  8. def __init__(self, key):
  9. self.bs = 32
  10. self.key = hashlib.sha256(key.encode()).digest()
  11.  
  12. def encrypt(self, raw):
  13. raw = self._pad(raw)
  14. iv = Random.new().read(AES.block_size)
  15. cipher = AES.new(self.key, AES.MODE_CBC, iv)
  16. return base64.b64encode(iv + cipher.encrypt(raw))
  17.  
  18. def decrypt(self, enc):
  19. enc = base64.b64decode(enc)
  20. iv = enc[:AES.block_size]
  21. cipher = AES.new(self.key, AES.MODE_CBC, iv)
  22. return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')
  23.  
  24. def _pad(self, s):
  25. return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)
  26.  
  27. @staticmethod
  28. def _unpad(s):
  29. return s[:-ord(s[len(s)-1:])]
  30.  
  31.  
  32. key = 'test'
  33. AES_test = AESCipher(key)
  34.  
  35. enc = AES_test.encrypt('how are you?')
  36. print "Let\'s encrypt plain text \"How are you?\" -> " + enc
  37. dec = AES_test.decrypt(enc)
  38. print "Let\'s decrypt cipher text -> " + dec
Success #stdin #stdout 0.02s 11400KB
stdin
Standard input is empty
stdout
Let's encrypt plain text "How are you?" -> hhskcf0E1hz9P10FSvbq2XXMLCrm1c7HRVTc1rA8mHnVDUvltsDg5igZU9u/Zy97
Let's decrypt cipher text -> how are you?