cl1p.net - The internet clipboard
Login/Sign Up
cl1p.net/lala
cl1p.net/lala
Login/Sign Up
This cl1p will be deleted in in 3 hours.
Copy
from Crypto.Cipher import AES from Crypto.Random import get_random_bytes import base64 # Function to pad data to make it a multiple of AES block size (16 bytes) def pad(data): # Padding length is the number of bytes needed to complete the block size padding_length = AES.block_size - len(data) % AES.block_size return data + chr(padding_length) * padding_length # Function to unpad the data def unpad(data): padding_length = ord(data[-1]) return data[:-padding_length] # AES Encryption def encrypt_data(key, data): # Pad the data before encryption padded_data = pad(data) # Create a new AES cipher with the given key and a random IV cipher = AES.new(key, AES.MODE_CBC) # Encrypt the data encrypted_data = cipher.encrypt(padded_data.encode()) # Return the IV + encrypted data (IV is necessary for decryption) return base64.b64encode(cipher.iv + encrypted_data).decode() # AES Decryption def decrypt_data(key, encrypted_data): # Decode the base64 encoded data encrypted_data = base64.b64decode(encrypted_data) # Extract the IV and encrypted data iv = encrypted_data[:AES.block_size] encrypted_data = encrypted_data[AES.block_size:] # Create a new AES cipher with the same key and IV used for encryption cipher = AES.new(key, AES.MODE_CBC, iv) # Decrypt the data decrypted_data = cipher.decrypt(encrypted_data) # Unpad the decrypted data return unpad(decrypted_data.decode()) # Example usage: if __name__ == "__main__": # 256-bit key for AES (must be either 16, 24, or 32 bytes long) key = get_random_bytes(32) # Generate a random 32-byte key # Data to encrypt data = "This is a secret message." # Encrypt the data encrypted = encrypt_data(key, data) print("Encrypted:", encrypted) # Decrypt the data decrypted = decrypt_data(key, encrypted) print("Decrypted:", decrypted)