import binascii
from Crypto.Cipher import AES
from Crypto.Util import Counter
from Crypto import Random
# AES supports multiple key sizes: 16 (AES128), 24 (AES192),
# or 32 (AES256).
key_bytes = 32
# You need to define 32-byte key. Like
# Key = '01234567890123456789012345678901'
# Please refer this page on how to create key.
# Otherwise you will get this error.
# Takes as input a 32-byte key and an arbitrary-length
# plaintext and returns a pair (iv, ciphtertext). "iv" stands for
# initialization vector.
def encrypt(key, plaintext):
assert len(key) == key_bytes
# Choose a random, 16-byte IV.
iv = Random.new().read(AES.block_size)
# Convert the IV to a Python integer.
iv_int = int(binascii.hexlify(iv), 16)
# Create a new Counter object with IV = iv_int.
ctr = Counter.new(AES.block_size * 8, initial_value=iv_int)
# Create AES-CTR cipher.
aes = AES.new(key, AES.MODE_CTR, counter=ctr)
# Encrypt and return IV and ciphertext.
ciphertext = aes.encrypt(plaintext)
return (iv, ciphertext)
# Takes as input a 32-byte key, a 16-byte IV, and a ciphertext,
# and outputs the corresponding plaintext.
def decrypt(key, iv, ciphertext):
assert len(key) == key_bytes
# Initialize counter for decryption. iv should be
# the same as the output of encrypt().
iv_int = int(iv.encode('hex'), 16)
ctr = Counter.new(AES.block_size * 8, initial_value=iv_int)
# Create AES-CTR cipher.
aes = AES.new(key, AES.MODE_CTR, counter=ctr)
# Decrypt and return the plaintext.
plaintext = aes.decrypt(ciphertext)
return plaintext
key = '01234567890123456789012345678901'
(iv, ciphertext) = encrypt(key, 'Coronavirus')
print (decrypt(key, iv, ciphertext))
aW1wb3J0IGJpbmFzY2lpCmZyb20gQ3J5cHRvLkNpcGhlciBpbXBvcnQgQUVTCmZyb20gQ3J5cHRvLlV0aWwgaW1wb3J0IENvdW50ZXIKZnJvbSBDcnlwdG8gaW1wb3J0IFJhbmRvbQoKIyBBRVMgc3VwcG9ydHMgbXVsdGlwbGUga2V5IHNpemVzOiAxNiAoQUVTMTI4KSwgMjQgKEFFUzE5MiksIAojIG9yIDMyIChBRVMyNTYpLgprZXlfYnl0ZXMgPSAzMgojIF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