fork download
  1. import binascii
  2. from Crypto.Cipher import AES
  3. from Crypto.Util import Counter
  4. from Crypto import Random
  5.  
  6. # AES supports multiple key sizes: 16 (AES128), 24 (AES192), or 32 (AES256).
  7. key_bytes = 32
  8.  
  9. # Takes as input a 32-byte key and an arbitrary-length plaintext and returns a pair (iv, ciphertext). "iv" stands for initialization vector.
  10. def encrypt(key, plaintext):
  11. assert len(key) == key_bytes
  12.  
  13. # Choose a random, 16-byte IV.
  14. iv = Random.new().read(AES.block_size)
  15.  
  16. # Convert the IV to a Python integer.
  17. iv_int = int(binascii.hexlify(iv), 16)
  18.  
  19. # Create a new Counter object with IV = iv_int.
  20. ctr = Counter.new(AES.block_size * 8, initial_value=iv_int)
  21.  
  22. # Create AES-CTR cipher.
  23. aes = AES.new(key, AES.MODE_CTR, counter=ctr)
  24.  
  25. # Encrypt and return IV and ciphertext.
  26. ciphertext = aes.encrypt(plaintext.encode('utf-8'))
  27. return (iv, ciphertext)
  28.  
  29. # Takes as input a 32-byte key, a 16-byte IV, and a ciphertext, and outputs the corresponding plaintext.
  30. def decrypt(key, iv, ciphertext):
  31. assert len(key) == key_bytes
  32.  
  33. # Initialize counter for decryption. iv should be the same as the output of encrypt().
  34. iv_int = int(binascii.hexlify(iv), 16)
  35. ctr = Counter.new(AES.block_size * 8, initial_value=iv_int)
  36.  
  37. # Create AES-CTR cipher.
  38. aes = AES.new(key, AES.MODE_CTR, counter=ctr)
  39.  
  40. # Decrypt and return the plaintext.
  41. plaintext = aes.decrypt(ciphertext)
  42. return plaintext.decode('utf-8')
  43.  
  44. # Example usage
  45. key = '01234567890123456789012345678901'.encode('utf-8')
  46. (iv, ciphertext) = encrypt(key, 'Coronavirus')
  47. plaintext = decrypt(key, iv, ciphertext)
  48.  
  49. print("Ciphertext: {}".format(binascii.hexlify(ciphertext).decode('utf-8')))
  50. print("Decrypted plaintext: {}".format(plaintext))
Success #stdin #stdout 0.03s 11440KB
stdin
Standard input is empty
stdout
Ciphertext: 6fbcc5742d4438eb8711a4
Decrypted plaintext: Coronavirus