tahamajs/NS / NetSec /CA /CA2 /aes_encryption.py
tahamajs's picture
download
raw
1.77 kB
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
def print_hex(label, data):
print(f"{label}: {data.hex()}")
def encrypt_decrypt_AES(plaintext):
key = get_random_bytes(16)
print("\nOriginal Plaintext:", plaintext)
if isinstance(plaintext, str):
plaintext = plaintext.encode()
padded_data = pad(plaintext, AES.block_size)
print("\nOriginal text length:", len(plaintext), "bytes")
print("Padded text length:", len(padded_data), "bytes")
print("Padded text in hex:", padded_data.hex())
encrypt_decrypt_ECB(key, padded_data)
encrypt_decrypt_CBC(key, padded_data)
def encrypt_decrypt_ECB(key, padded_data):
print("\n=== ECB Mode ===")
cipher_ecb = AES.new(key, AES.MODE_ECB)
ciphertext_ecb = cipher_ecb.encrypt(padded_data)
print_hex("Ciphertext (ECB)", ciphertext_ecb)
decipher_ecb = AES.new(key, AES.MODE_ECB)
decrypted_ecb = unpad(decipher_ecb.decrypt(ciphertext_ecb), AES.block_size)
print("Decrypted text (ECB):", decrypted_ecb.decode())
print("===")
def encrypt_decrypt_CBC(key, padded_data):
print("\n=== CBC Mode ===")
cipher_cbc = AES.new(key, AES.MODE_CBC)
ciphertext_cbc = cipher_cbc.encrypt(padded_data)
print_hex("IV (CBC)", cipher_cbc.iv)
print_hex("Ciphertext (CBC)", ciphertext_cbc)
decipher_cbc = AES.new(key, AES.MODE_CBC, iv=cipher_cbc.iv)
decrypted_cbc = unpad(decipher_cbc.decrypt(ciphertext_cbc), AES.block_size)
print("Decrypted text (CBC):", decrypted_cbc.decode())
print("===")
def main():
sample_text = "This is a Test for Implementation of AES"
encrypt_decrypt_AES(sample_text)
if __name__ == "__main__":
main()

Xet Storage Details

Size:
1.77 kB
·
Xet hash:
d506d41edabfac3e9f70ba705b70d59d7ea151ddd55b8e0c17852056d14bfde7

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.