fork download
  1. from Crypto.Cipher import AES # AES crypto
  2. from Crypto.Random import get_random_bytes
  3.  
  4. def add_padding(msg):
  5. if len(msg) % 16 != 0:
  6. # message length must be a factor of 16!!!
  7. nb_of_chars_to_pad = 16 - (len(msg) % 16)
  8. padded_msg = msg + (" " * nb_of_chars_to_pad)
  9. return padded_msg
  10. # message length is already a factor of 16
  11. return msg
  12.  
  13. def encrypt_message(plaintext, key, initialization_vector):
  14. # pad the msg if necessary
  15. plaintext = add_padding(plaintext)
  16. plaintext_bytes = plaintext.encode("utf_8")
  17. # create a new AES cypher. AES hasn't been broken yet, so we're safe as long as no one knows our key!
  18. # we use CBC mode, so we need an initialization vector.
  19. cipher = AES.new(key, AES.MODE_CBC, initialization_vector)
  20. ciphertext = cipher.encrypt(plaintext_bytes)
  21. return ciphertext
  22.  
  23.  
  24.  
  25. def decrypt_message(ciphertext, key, initialization_vector):
  26. if (len(ciphertext) % 16) != 0:
  27. print("Cipher has not the correct length, this was not encrypted by us.")
  28. #return
  29. cipher = AES.new(key, AES.MODE_CBC, initialization_vector)
  30. plaintext = cipher.decrypt(ciphertext)
  31. return plaintext
  32.  
  33. # create key and initialization vector
  34. secret_key = b"_fl{CR-mCpaxyep}" # must be 16 bytes
  35. secret_initialization_vector = secret_key
  36.  
  37. print(encrypt_message("aaaaaaaaaaaaaaaa", secret_key, secret_initialization_vector))
Success #stdin #stdout 0.03s 11304KB
stdin
Standard input is empty
stdout
��0�1o��}Ө���7