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),
  7. # or 32 (AES256).
  8. key_bytes = 32
  9. # You need to define 32-byte key. Like
  10. # Key = '01234567890123456789012345678901'
  11. # Please refer this page on how to create key.
  12.  
  13. # Otherwise you will get this error.
  14.  
  15. # Takes as input a 32-byte key and an arbitrary-length
  16. # plaintext and returns a pair (iv, ciphtertext). "iv" stands for
  17. # initialization vector.
  18. def encrypt(key, plaintext):
  19. assert len(key) == key_bytes
  20.  
  21. # Choose a random, 16-byte IV.
  22. iv = Random.new().read(AES.block_size)
  23.  
  24. # Convert the IV to a Python integer.
  25. iv_int = int(binascii.hexlify(iv), 16)
  26.  
  27. # Create a new Counter object with IV = iv_int.
  28. ctr = Counter.new(AES.block_size * 8, initial_value=iv_int)
  29.  
  30. # Create AES-CTR cipher.
  31. aes = AES.new(key, AES.MODE_CTR, counter=ctr)
  32.  
  33. # Encrypt and return IV and ciphertext.
  34. ciphertext = aes.encrypt(plaintext)
  35. return (iv, ciphertext)
  36.  
  37. # Takes as input a 32-byte key, a 16-byte IV, and a ciphertext,
  38. # and outputs the corresponding plaintext.
  39. def decrypt(key, iv, ciphertext):
  40. assert len(key) == key_bytes
  41.  
  42. # Initialize counter for decryption. iv should be
  43. # the same as the output of encrypt().
  44. iv_int = int(iv.encode('hex'), 16)
  45. ctr = Counter.new(AES.block_size * 8, initial_value=iv_int)
  46.  
  47. # Create AES-CTR cipher.
  48. aes = AES.new(key, AES.MODE_CTR, counter=ctr)
  49.  
  50. # Decrypt and return the plaintext.
  51. plaintext = aes.decrypt(ciphertext)
  52. return plaintext
  53.  
  54. key = '01234567890123456789012345678901'
  55. (iv, ciphertext) = encrypt(key, 'Coronavirus')
  56. print (decrypt(key, iv, ciphertext))
Success #stdin #stdout 0.02s 11428KB
stdin
Standard input is empty
stdout
Coronavirus