From 55106adc2e288bc274d8beb934ab0d2bd636889d Mon Sep 17 00:00:00 2001 From: grpathak22 Date: Thu, 3 Oct 2024 23:19:29 +0530 Subject: [PATCH 1/2] added aes-128 algorithm in ciphers Signed-off-by: grpathak22 --- ciphers/aes-128.py | 61 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 ciphers/aes-128.py diff --git a/ciphers/aes-128.py b/ciphers/aes-128.py new file mode 100644 index 000000000000..e0ba4f4825ea --- /dev/null +++ b/ciphers/aes-128.py @@ -0,0 +1,61 @@ +from Crypto.Cipher import AES +from Crypto.Util.Padding import pad, unpad +import base64 + +def aes_encrypt(plaintext: str, key: str) -> str: + """ + AES-128 Encryption using CBC mode and PKCS7 padding. + + :param plaintext: The plaintext message to be encrypted. + :param key: The encryption key (16 characters = 128 bits). + :return: Encrypted message (Base64 encoded). + + >>> msg = "This is a secret message." + >>> key = "thisisaverysecret" + >>> enc = aes_encrypt(msg, key) + >>> dec = aes_decrypt(enc, key) + >>> aes_decrypt(enc, key) == msg + True + """ + cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC) + ciphertext = cipher.encrypt(pad(plaintext.encode('utf-8'), AES.block_size)) + return base64.b64encode(cipher.iv + ciphertext).decode('utf-8') + +def aes_decrypt(ciphertext: str, key: str) -> str: + """ + AES-128 Decryption using CBC mode and PKCS7 padding. + + :param ciphertext: The Base64 encoded encrypted message. + :param key: The decryption key (16 characters = 128 bits). + :return: Decrypted plaintext message. + + >>> msg = "This is a secret message." + >>> key = "thisisaverysecret" + >>> enc = aes_encrypt(msg, key) + >>> dec = aes_decrypt(enc, key) + >>> dec == msg + True + """ + raw = base64.b64decode(ciphertext) + cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv=raw[:AES.block_size]) + return unpad(cipher.decrypt(raw[AES.block_size:]), AES.block_size).decode('utf-8') + +def main() -> None: + key = input("Enter 16-character key (AES-128): ") + if len(key) != 16: + raise ValueError("Key must be 16 characters long!") + + message = input("Enter message: ") + + # Encryption + encrypted_message = aes_encrypt(message, key) + print("Encrypted message:", encrypted_message) + + # Decryption + decrypted_message = aes_decrypt(encrypted_message, key) + print("Decrypted message:", decrypted_message) + +if __name__ == "__main__": + import doctest + doctest.testmod() + main() From feb9da47b12fd4fd32e3a64051496028a911dd47 Mon Sep 17 00:00:00 2001 From: grpathak22 Date: Thu, 3 Oct 2024 23:22:20 +0530 Subject: [PATCH 2/2] added aes-128 algorithm in ciphers Signed-off-by: grpathak22 --- ciphers/{aes-128.py => aes_128.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename ciphers/{aes-128.py => aes_128.py} (100%) diff --git a/ciphers/aes-128.py b/ciphers/aes_128.py similarity index 100% rename from ciphers/aes-128.py rename to ciphers/aes_128.py