import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES
class AESCipher(object):
def __init__(self, key):
self.bs = 32
self.key = hashlib.sha256(key.encode()).digest()
def encrypt(self, raw):
raw = self._pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(raw))
def decrypt(self, enc):
enc = base64.b64decode(enc)
iv = enc[:AES.block_size]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')
def _pad(self, s):
return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)
@staticmethod
def _unpad(s):
return s[:-ord(s[len(s)-1:])]
key = 'test'
AES_test = AESCipher(key)
enc = AES_test.encrypt('Coronavirus')
print "Let\'s encrypt plain text \"Coronavirus\" -> " + enc
dec = AES_test.decrypt(enc)
print "Let\'s decrypt cipher text -> " + dec
aW1wb3J0IGJhc2U2NAppbXBvcnQgaGFzaGxpYgpmcm9tIENyeXB0byBpbXBvcnQgUmFuZG9tCmZyb20gQ3J5cHRvLkNpcGhlciBpbXBvcnQgQUVTCgpjbGFzcyBBRVNDaXBoZXIob2JqZWN0KToKCiAgIGRlZiBfX2luaXRfXyhzZWxmLCBrZXkpOgogICAgICBzZWxmLmJzID0gMzIKICAgICAgc2VsZi5rZXkgPSBoYXNobGliLnNoYTI1NihrZXkuZW5jb2RlKCkpLmRpZ2VzdCgpCgogICBkZWYgZW5jcnlwdChzZWxmLCByYXcpOgogICAgICByYXcgPSBzZWxmLl9wYWQocmF3KQogICAgICBpdiA9IFJhbmRvbS5uZXcoKS5yZWFkKEFFUy5ibG9ja19zaXplKQogICAgICBjaXBoZXIgPSBBRVMubmV3KHNlbGYua2V5LCBBRVMuTU9ERV9DQkMsIGl2KQogICAgICByZXR1cm4gYmFzZTY0LmI2NGVuY29kZShpdiArIGNpcGhlci5lbmNyeXB0KHJhdykpCgogICBkZWYgZGVjcnlwdChzZWx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