Last active
November 6, 2024 08:12
-
-
Save lopes/168c9d74b988391e702aac5f4aa69e41 to your computer and use it in GitHub Desktop.
Simple Python example of AES in CBC mode. #python #cryptography #aes #cbc #poc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# | |
# This is a simple script to encrypt a message using AES | |
# with CBC mode in Python 3. | |
# Before running it, you must install pycryptodome: | |
# | |
# $ python -m pip install PyCryptodome | |
# | |
# Author.: José Lopes | |
# Date...: 2019-06-14 | |
# License: MIT | |
## | |
from hashlib import md5 | |
from base64 import b64decode | |
from base64 import b64encode | |
from Crypto.Cipher import AES | |
from Crypto.Random import get_random_bytes | |
from Crypto.Util.Padding import pad, unpad | |
class AESCipher: | |
def __init__(self, key): | |
self.key = md5(key.encode('utf8')).digest() | |
def encrypt(self, data): | |
iv = get_random_bytes(AES.block_size) | |
self.cipher = AES.new(self.key, AES.MODE_CBC, iv) | |
return b64encode(iv + self.cipher.encrypt(pad(data.encode('utf-8'), | |
AES.block_size))) | |
def decrypt(self, data): | |
raw = b64decode(data) | |
self.cipher = AES.new(self.key, AES.MODE_CBC, raw[:AES.block_size]) | |
return unpad(self.cipher.decrypt(raw[AES.block_size:]), AES.block_size) | |
if __name__ == '__main__': | |
print('TESTING ENCRYPTION') | |
msg = input('Message...: ') | |
pwd = input('Password..: ') | |
print('Ciphertext:', AESCipher(pwd).encrypt(msg).decode('utf-8')) | |
print('\nTESTING DECRYPTION') | |
cte = input('Ciphertext: ') | |
pwd = input('Password..: ') | |
print('Message...:', AESCipher(pwd).decrypt(cte).decode('utf-8')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have found the solution that work perfectly for me:
Code Reference : https://yococoxc.github.io/15493867450071.html