import os import numpy as np from PIL import Image from cryptography.fernet import Fernet def encrypt_image(image_path): img = Image.open(image_path).convert("L") arr = np.array(img) # Save pixel values os.makedirs("send", exist_ok=True) np.savetxt("send/pixel_values.txt", arr, fmt="%d") print("Pixel values saved to send/pixel_values.txt") # Break into 2x2 blocks blocks = [] h, w = arr.shape for i in range(0, h, 2): for j in range(0, w, 2): block = arr[i:i+2, j:j+2] if block.shape == (2, 2): blocks.append(block.flatten()) np.savetxt("send/blocks.txt", blocks, fmt="%d") print("2x2 matrices with block numbers saved to send/blocks.txt") # Key 1: shuffle block order key1 = Fernet.generate_key() fernet1 = Fernet(key1) indices = np.arange(len(blocks)) np.random.shuffle(indices) with open("send/shuffled_blocks_aes.txt", "wb") as f: f.write(fernet1.encrypt(str(indices.tolist()).encode())) print("Key for block shuffling: ", key1) # Key 2: shuffle inside blocks key2 = Fernet.generate_key() fernet2 = Fernet(key2) perm = [0, 1, 2, 3] np.random.shuffle(perm) with open("send/shuffled_blocks_aes_after_block_shuffling.txt", "wb") as f: f.write(fernet2.encrypt(str(perm).encode())) print("Key for within block shuffling: ", key2) # Save keys os.makedirs("out", exist_ok=True) with open("out/keys.txt", "w") as f: f.write(key1.decode() + "\n") f.write(key2.decode() + "\n") # Save encrypted image (same as cover for now) Image.fromarray(arr).save("encrypted_image.png") print("Encrypted image saved to encrypted_image.png")