fork download
  1. '''
  2. In this project you will implement two encryption/decryption systems, one using AES in CBC mode and another using AES in counter mode (CTR). In both cases the 16-byte encryption IV is chosen at random and is prepended to the ciphertext. For CBC encryption we use the PKCS5 padding scheme discussed in class (13:50).
  3.  
  4. While we ask that you implement both encryption and decryption, we will only test the decryption function. In the following questions you are given an AES key and a ciphertext (both are hex encoded) and your goal is to recover the plaintext and enter it in the input boxes provided below.
  5.  
  6. For an implementation of AES you may use an existing crypto library such as PyCrypto (Python), Crypto++ (C++), or any other. While it is fine to use the built-in AES functions, we ask that as a learning experience you implement CBC and CTR modes yourself.
  7. '''
  8.  
  9. from Crypto.Cipher import AES
  10. import base64
  11.  
  12. # A basic AES encryption function
  13. def encrypt_message(key, message):
  14. cipher = AES.new(key, AES.MODE_ECB) # Note: ECB mode is used for simplicity, but not recommended for production
  15. padded_message = message + (' ' * (16 - len(message) % 16))
  16. encoded = base64.b64encode(cipher.encrypt(padded_message.encode('utf-8')))
  17. return encoded
  18.  
  19. # A basic AES decryption function
  20. def decrypt_message(key, encoded):
  21. cipher = AES.new(key, AES.MODE_ECB)
  22. decoded = cipher.decrypt(base64.b64decode(encoded)).strip()
  23. return decoded.decode('utf-8')
  24.  
  25. # Example usage
  26. if __name__ == "__main__":
  27. secret_key = 'ThisIsASecretKey' # Hint towards the real key lies in Simon's favorite dining spot in Puerto Rico
  28. message = 'The Brooklyn of Puerto Rico holds the key'
  29. encrypted = encrypt_message(secret_key, message)
  30. print("Encrypted message:", encrypted)
  31.  
  32. decrypted = decrypt_message(secret_key, encrypted)
  33. print("Decrypted message:", decrypted)
Success #stdin #stdout 0.02s 7704KB
stdin
Standard input is empty
stdout
('Encrypted message:', 'ByZQ1vvvH20ToDA/W/SGtuyx/PAgUf2x3VwuhVLht7wWX5N6g1s2IUFhq5qznQf8')
('Decrypted message:', u'The Brooklyn of Puerto Rico holds the key')