import binascii
from Crypto.Cipher import AES
from Crypto.Util import Counter
from Crypto import Random
key_bytes = 32
def encrypt(key, plaintext):
assert len(key) == key_bytes
iv = Random.new().read(AES.block_size)
iv_int = int(binascii.hexlify(iv), 16)
ctr = Counter.new(AES.block_size * 8, initial_value=iv_int)
aes = AES.new(key, AES.MODE_CTR, counter=ctr)
ciphertext = aes.encrypt(plaintext)
return (iv, ciphertext)
def decrypt(key, iv, ciphertext):
assert len(key) == key_bytes
iv_int = int(iv.encode('hex'), 16)
ctr = Counter.new(AES.block_size * 8, initial_value=iv_int)
aes = AES.new(key, AES.MODE_CTR, counter=ctr)
plaintext = aes.decrypt(ciphertext)
return plaintext
key = '01234567890123456789012345678901'
(iv, ciphertext) = encrypt(key, 'Coronavirus')
print (decrypt(key, iv, ciphertext))
aW1wb3J0IGJpbmFzY2lpCmZyb20gQ3J5cHRvLkNpcGhlciBpbXBvcnQgQUVTCmZyb20gQ3J5cHRvLlV0aWwgaW1wb3J0IENvdW50ZXIKZnJvbSBDcnlwdG8gaW1wb3J0IFJhbmRvbQoKa2V5X2J5dGVzID0gMzIKCmRlZiBlbmNyeXB0KGtleSwgcGxhaW50ZXh0KToKICAgIGFzc2VydCBsZW4oa2V5KSA9PSBrZXlfYnl0ZXMKCiAgICBpdiA9IFJhbmRvbS5uZXcoKS5yZWFkKEFFUy5ibG9ja19zaXplKQoKICAgIGl2X2ludCA9IGludChiaW5hc2NpaS5oZXhsaWZ5KGl2KSwgMTYpIAoKICAgIGN0ciA9IENvdW50ZXIubmV3KEFFUy5ibG9ja19zaXplICogOCwgaW5pdGlhbF92YWx1ZT1pdl9pbnQpCgogICAgYWVzID0gQUVTLm5ldyhrZXksIEFFUy5NT0RFX0NUUiwgY291bnRlcj1jdHIpCgogICAgY2lwaGVydGV4dCA9IGFlcy5lbmNyeXB0KHBsYWludGV4dCkKICAgIHJldHVybiAoaXYsIGNpcGhlcnRleHQpCgpkZWYgZGVjcnlwdChrZXksIGl2LCBjaXBoZXJ0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