fork download
  1. import binascii
  2. from Crypto.Cipher import AES
  3. from Crypto.Util import Counter
  4. from Crypto import Random
  5.  
  6. key_bytes = 32
  7.  
  8. def encrypt(key, plaintext):
  9. assert len(key) == key_bytes
  10.  
  11. iv = Random.new().read(AES.block_size)
  12.  
  13. iv_int = int(binascii.hexlify(iv), 16)
  14.  
  15. ctr = Counter.new(AES.block_size * 8, initial_value=iv_int)
  16.  
  17. aes = AES.new(key, AES.MODE_CTR, counter=ctr)
  18.  
  19. ciphertext = aes.encrypt(plaintext)
  20. return (iv, ciphertext)
  21.  
  22. def decrypt(key, iv, ciphertext):
  23. assert len(key) == key_bytes
  24.  
  25. iv_int = int(iv.encode('hex'), 16)
  26. ctr = Counter.new(AES.block_size * 8, initial_value=iv_int)
  27.  
  28. aes = AES.new(key, AES.MODE_CTR, counter=ctr)
  29.  
  30. plaintext = aes.decrypt(ciphertext)
  31. return plaintext
  32.  
  33. key = '01234567890123456789012345678901'
  34. (iv, ciphertext) = encrypt(key, 'Coronavirus')
  35. print (decrypt(key, iv, ciphertext))
Success #stdin #stdout 0.02s 11392KB
stdin
Standard input is empty
stdout
Coronavirus