2
2
from Crypto .Util .Padding import pad , unpad
3
3
import base64
4
4
5
+
5
6
def aes_encrypt (plaintext : str , key : str ) -> str :
6
7
"""
7
8
AES-128 Encryption using CBC mode and PKCS7 padding.
@@ -17,9 +18,10 @@ def aes_encrypt(plaintext: str, key: str) -> str:
17
18
>>> aes_decrypt(enc, key) == msg
18
19
True
19
20
"""
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' )
21
+ cipher = AES .new (key .encode ("utf-8" ), AES .MODE_CBC )
22
+ ciphertext = cipher .encrypt (pad (plaintext .encode ("utf-8" ), AES .block_size ))
23
+ return base64 .b64encode (cipher .iv + ciphertext ).decode ("utf-8" )
24
+
23
25
24
26
def aes_decrypt (ciphertext : str , key : str ) -> str :
25
27
"""
@@ -37,8 +39,9 @@ def aes_decrypt(ciphertext: str, key: str) -> str:
37
39
True
38
40
"""
39
41
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
+ cipher = AES .new (key .encode ("utf-8" ), AES .MODE_CBC , iv = raw [: AES .block_size ])
43
+ return unpad (cipher .decrypt (raw [AES .block_size :]), AES .block_size ).decode ("utf-8" )
44
+
42
45
43
46
def main () -> None :
44
47
key = input ("Enter 16-character key (AES-128): " )
@@ -55,7 +58,9 @@ def main() -> None:
55
58
decrypted_message = aes_decrypt (encrypted_message , key )
56
59
print ("Decrypted message:" , decrypted_message )
57
60
61
+
58
62
if __name__ == "__main__" :
59
63
import doctest
64
+
60
65
doctest .testmod ()
61
66
main ()
0 commit comments