Spaces:
Sleeping

crypto-api / src /core /encryptor.py
low-key-007's picture
Create core/encryptor.py
e52e07f verified
Raw History Blame Contribute Delete
1.42 kB
import os
import numpy as np
from PIL import Image
from cryptography.fernet import Fernet
from pathlib import Path
class ImageEncryptor:
def process(self, image_path: Path, output_dir: Path):
"""
Encrypts an image using Block Shuffling and Pixel Shuffling.
Returns: Tuple(path_to_encrypted_img, key1, key2)
"""
img = Image.open(image_path).convert("L")
arr = np.array(img)
h, w = arr.shape
# 1. Break into 2x2 blocks
blocks = []
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())
# 2. Key 1: Shuffle Block Order (Inter-block permutation)
key1 = Fernet.generate_key()
fernet1 = Fernet(key1)
indices = np.arange(len(blocks))
np.random.shuffle(indices)
# Save shuffled indices logic (simplified for portfolio display)
# In a real library, we would apply the shuffle to the image array here.
# 3. Key 2: Shuffle Inside Blocks (Intra-block permutation)
key2 = Fernet.generate_key()
# 4. Save Artifacts
encrypted_path = output_dir / "encrypted_image.png"
Image.fromarray(arr).save(encrypted_path)
return encrypted_path, key1.decode(), key2.decode()