Загрузка данных
import os
import random
import string
import cv2
import numpy as np
from Crypto.Cipher import AES
from Crypto.Util import Counter
ENCRYPTED_FILE = "encrypted.avi"
DECRYPTED_FILE = "decrypted.avi"
SETTINGS_FILE = "setting.txt"
def find_input_file():
"""Поиск файла object с любым расширением"""
supported_extensions = ['.mp4', '.avi', '.mov', '.mkv', '.png', '.jpg', '.jpeg', '.webp']
for ext in supported_extensions:
filename = f"object{ext}"
if os.path.exists(filename):
return filename
return None
def generate_token(length=32):
"""Генерация токена с помощью стандартного модуля random"""
chars = string.ascii_letters + string.digits
return ''.join(random.choice(chars) for _ in range(length))
def token_to_key_and_iv(token: str):
"""
Превращаем произвольный токен в 32-байтный ключ и 16-байтный IV
без использования библиотеки hashlib.
"""
token_bytes = token.encode('utf-8')
# Подгоняем ключ под ровно 32 байта
if len(token_bytes) >= 32:
key = token_bytes[:32]
else:
# Дополняем нулями до 32 байт, если токен короткий
key = token_bytes.ljust(32, b'\x00')
# Формируем IV (16 байт) на основе развернутого ключа
iv = key[16:32]
return key, iv
def encrypt_decrypt_bytes(data_bytes: bytes, key: bytes, iv: bytes, frame_index: int) -> bytes:
"""Шифрование/Дешифрование байтов через AES-CTR"""
ctr_int = int.from_bytes(iv, 'big') + frame_index
ctr = Counter.new(128, initial_value=ctr_int)
cipher = AES.new(key, AES.MODE_CTR, counter=ctr)
return cipher.encrypt(data_bytes)
def process_media(in_path: str, out_path: str, token: str):
key, iv = token_to_key_and_iv(token)
is_image = in_path.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))
print(f"Чтение файла [{in_path}]...")
if is_image:
# --- ОБРАБОТКА ИЗОБРАЖЕНИЯ (PNG / JPG) ---
frame = cv2.imread(in_path)
if frame is None:
print(f"[!] Ошибка: Не удалось прочитать картинку {in_path}")
return
height, width, _ = frame.shape
raw_bytes = frame.tobytes()
# Шифруем пиксели картинки
processed_bytes = encrypt_decrypt_bytes(raw_bytes, key, iv, frame_index=0)
processed_frame = np.frombuffer(processed_bytes, dtype=np.uint8).reshape((height, width, 3))
# Сохраняем видео из 1 кадра с несжатым кодеком FFV1
fourcc = cv2.VideoWriter_fourcc(*'FFV1')
out = cv2.VideoWriter(out_path, fourcc, 1.0, (width, height))
out.write(processed_frame)
out.release()
print(f"[✓] Успешно! Файл шума сохранен в {out_path}")
else:
# --- ОБРАБОТКА ВИДЕО (MP4 / AVI) ---
cap = cv2.VideoCapture(in_path)
if not cap.isOpened():
print(f"[!] Ошибка: Не удалось открыть видео {in_path}")
return
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)
if fps == 0:
fps = 30.0
fourcc = cv2.VideoWriter_fourcc(*'FFV1')
out = cv2.VideoWriter(out_path, fourcc, fps, (width, height))
frame_index = 0
print(f"Обработка кадров видео...")
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
raw_bytes = frame.tobytes()
processed_bytes = encrypt_decrypt_bytes(raw_bytes, key, iv, frame_index)
processed_frame = np.frombuffer(processed_bytes, dtype=np.uint8).reshape((height, width, 3))
out.write(processed_frame)
frame_index += 1
cap.release()
out.release()
print(f"[✓] Видео успешно обработано! Кадров: {frame_index}. Файл: {out_path}")
def encrypt_mode():
input_file = find_input_file()
if not input_file:
print("[!] В папке со скриптом не найден файл 'object' (.png, .jpg, .mp4)!")
return
print(f"[+] Найден файл для шифрования: {input_file}")
token = generate_token()
with open(SETTINGS_FILE, "w", encoding="utf-8") as f:
f.write(token)
print(f"[+] Новый токен записан в {SETTINGS_FILE}: {token}")
process_media(input_file, ENCRYPTED_FILE, token)
def decrypt_mode():
if not os.path.exists(ENCRYPTED_FILE):
print(f"[!] Файл {ENCRYPTED_FILE} не найден!")
return
if not os.path.exists(SETTINGS_FILE):
print(f"[!] Файл {SETTINGS_FILE} не найден!")
return
with open(SETTINGS_FILE, "r", encoding="utf-8") as f:
token = f.read().strip()
print(f"[+] Считан токен из {SETTINGS_FILE}: {token}")
process_media(ENCRYPTED_FILE, DECRYPTED_FILE, token)
if __name__ == "__main__":
print("Выберите режим:")
print("1 — Зашифровать (object.* -> encrypted.avi + создать setting.txt)")
print("2 — Расшифровать (encrypted.avi -> decrypted.avi по токену из setting.txt)")
choice = input("Введите цифру (1 или 2): ").strip()
if choice == "1":
encrypt_mode()
elif choice == "2":
decrypt_mode()
else:
print("[!] Неверный выбор.")