@Romeo558
Продолжающий программист на python.

Что не так с алгоритмом шифрования фотографий?

Пишу совершенно новый для себя проект: Алгоритм, который шифрует фотографию переставляя пиксели в фотографии с места на место используя своего рода ключ.
И он даже работает, но при этом теряется весь цвет фото и появляется цифровой шум на фотографии. Возможно дело в самом ключе или как он переставляет пиксели, но я так и не могу понять что нужно поменять.
Помогите пожалуйста те, кто может.

Код:
from PIL import Image
import numpy as np
import os

def generate_or_load_key():
    key_file = "image_key.key"

    # Check if the key file exists
    if os.path.exists(key_file):
        with open(key_file, "r") as file:
            key = file.read().strip()
    else:
        # Generate a random key if the file doesn't exist
        key = ''.join(np.random.choice(list('0123456789'), size=10))
        with open(key_file, "w") as file:
            file.write(key)

    return key

def convert_key_to_seed(key):
    # Convert the key to a single integer seed
    seed = int(key) % 4294967295
    return seed

def encrypt_image(image_path, key):
    # Open the image
    img = Image.open(image_path)
    img_array = np.array(img)

    # Get the shape of the image array
    height, width, channels = img_array.shape

    # Convert the key to a single seed
    seed = convert_key_to_seed(key)

    # Seed the random number generator
    np.random.seed(seed)

    # Generate a permutation of indices
    indices = np.arange(height * width)
    np.random.shuffle(indices)

    # Flatten and shuffle the image array for each channel
    encrypted_data = [img_array[:, :, i].ravel()[indices].reshape((height, width)) for i in range(channels)]

    # Stack the shuffled channels to reconstruct the image
    encrypted_data = np.stack(encrypted_data, axis=-1)

    # Save the encrypted image with a new file path
    encrypted_image_path = os.path.splitext(image_path)[0] + "_encrypted.jpg"
    encrypted_image = Image.fromarray(encrypted_data.astype('uint8'))
    encrypted_image.save(encrypted_image_path)

def decrypt_image(image_path, key):
    # Open the encrypted image
    encrypted_img = Image.open(image_path)
    encrypted_data = np.array(encrypted_img)

    # Get the shape of the image array
    height, width, channels = encrypted_data.shape

    # Convert the key to a single seed
    seed = convert_key_to_seed(key)

    # Seed the random number generator
    np.random.seed(seed)

    # Generate the same permutation of indices
    indices = np.arange(height * width)
    np.random.shuffle(indices)

    # Flatten and shuffle each channel separately
    decrypted_data = [encrypted_data[:, :, i].ravel()[np.argsort(indices)].reshape((height, width)) for i in range(channels)]

    # Stack the shuffled channels to reconstruct the original image
    decrypted_data = np.stack(decrypted_data, axis=-1)

    # Save the decrypted image with a new file path
    decrypted_image_path = os.path.splitext(image_path)[0] + "_decrypted.jpg"
    decrypted_image = Image.fromarray(decrypted_data.astype('uint8'))
    decrypted_image.save(decrypted_image_path)

# Example usage
original_image_path = "example_photos/15.jpg"
key = generate_or_load_key()
print(convert_key_to_seed(key))

encrypt_image(original_image_path, key)

decrypt_image(original_image_path.replace(".jpg", "_encrypted.jpg"), key)

print("Encryption and Decryption completed.")


Фото до:
spoiler
656e08b23b7b9764957047.jpeg


Фото после шифрации:
spoiler
656e08d0c90e8012658805.jpeg


Фото после восстановления:
spoiler
656e08e1ded18382245826.jpeg


Как видно, теряется почти весь цвет, но формы на фото остаются теми же.
Есть идеи как это могло произойти и как это исправить?
Крайне благодарен.
  • Вопрос задан
  • 240 просмотров
Решения вопроса 1
@U235U235
Никогда не используй сжатие с потерями jpeg для таких целей. Используй PNG.
Ответ написан
Пригласить эксперта
Ответы на вопрос 2
dimonchik2013
@dimonchik2013
non progredi est regredi
исправить это вот так
https://habr.com/ru/articles/413803/

а для возни с кодом нанимают фрилансера
Ответ написан
CityCat4
@CityCat4
Внимание! Изменился адрес почты!
Не особенно-то он и новый... Была в начале нулевых такая игра "Ранедву с незнакомкой". Рассчитана она была не только на компы, но и на запуск с dvd-плеера (sic!) Игра - обычный логический квест на раздевание. Так вот, чтобы хитрый юзер не посмотрел картинки сразу - они были примерно таким же образом пошифрованы. Сейчас возможно уже и не найти ничего, но дома у меня могли сохраниться исходники дешифратора, который я однажды нашел, когда некий чел написал его просто по фану...
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы