|
| 1 | +from Crypto.Cipher import AES |
| 2 | +from Crypto.Util.Padding import pad, unpad |
| 3 | +import base64 |
| 4 | + |
| 5 | +def aes_encrypt(plaintext: str, key: str) -> str: |
| 6 | + """ |
| 7 | + AES-128 Encryption using CBC mode and PKCS7 padding. |
| 8 | +
|
| 9 | + :param plaintext: The plaintext message to be encrypted. |
| 10 | + :param key: The encryption key (16 characters = 128 bits). |
| 11 | + :return: Encrypted message (Base64 encoded). |
| 12 | +
|
| 13 | + >>> msg = "This is a secret message." |
| 14 | + >>> key = "thisisaverysecret" |
| 15 | + >>> enc = aes_encrypt(msg, key) |
| 16 | + >>> dec = aes_decrypt(enc, key) |
| 17 | + >>> aes_decrypt(enc, key) == msg |
| 18 | + True |
| 19 | + """ |
| 20 | + cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC) |
| 21 | + ciphertext = cipher.encrypt(pad(plaintext.encode('utf-8'), AES.block_size)) |
| 22 | + return base64.b64encode(cipher.iv + ciphertext).decode('utf-8') |
| 23 | + |
| 24 | +def aes_decrypt(ciphertext: str, key: str) -> str: |
| 25 | + """ |
| 26 | + AES-128 Decryption using CBC mode and PKCS7 padding. |
| 27 | +
|
| 28 | + :param ciphertext: The Base64 encoded encrypted message. |
| 29 | + :param key: The decryption key (16 characters = 128 bits). |
| 30 | + :return: Decrypted plaintext message. |
| 31 | +
|
| 32 | + >>> msg = "This is a secret message." |
| 33 | + >>> key = "thisisaverysecret" |
| 34 | + >>> enc = aes_encrypt(msg, key) |
| 35 | + >>> dec = aes_decrypt(enc, key) |
| 36 | + >>> dec == msg |
| 37 | + True |
| 38 | + """ |
| 39 | + raw = base64.b64decode(ciphertext) |
| 40 | + cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv=raw[:AES.block_size]) |
| 41 | + return unpad(cipher.decrypt(raw[AES.block_size:]), AES.block_size).decode('utf-8') |
| 42 | + |
| 43 | +def main() -> None: |
| 44 | + key = input("Enter 16-character key (AES-128): ") |
| 45 | + if len(key) != 16: |
| 46 | + raise ValueError("Key must be 16 characters long!") |
| 47 | + |
| 48 | + message = input("Enter message: ") |
| 49 | + |
| 50 | + # Encryption |
| 51 | + encrypted_message = aes_encrypt(message, key) |
| 52 | + print("Encrypted message:", encrypted_message) |
| 53 | + |
| 54 | + # Decryption |
| 55 | + decrypted_message = aes_decrypt(encrypted_message, key) |
| 56 | + print("Decrypted message:", decrypted_message) |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + import doctest |
| 60 | + doctest.testmod() |
| 61 | + main() |
0 commit comments