Мне пришла мысль в голову: а может ling-1t написать нормальное шифрование. Т.к. я плохо разбираюсь в криптографии я хотел спросить людей, которые профессионалы в этой области. Вот код:
import os
import hmac
import hashlib
from itertools import count
from secrets import token_bytes
class QuantumResistantStreamCipher:
def __init__(self, key: bytes):
if len(key) != 32:
raise ValueError("Key must be 32 bytes (256 bits) for HMAC-SHA256 security.")
self.key = key
self.block_size = 64 # SHA256 block size in bytes (для HMAC)
def _generate_keystream(self, nonce: bytes, length: int):
"""Генерирует криптостойкий псевдослучайный поток на основе HMAC в CTR-режиме."""
if len(nonce) != 16:
raise ValueError("Nonce must be 16 bytes.")
keystream = bytearray()
# Используем HMAC(key, nonce || counter) как блоки потока
for ctr in count(0):
msg = nonce + ctr.to_bytes(8, 'big') # nonce(16) + ctr(8) = 24 байта
block = hmac.new(self.key, msg, hashlib.sha256).digest()
keystream.extend(block)
if len(keystream) >= length:
break
return bytes(keystream[:length])
def encrypt(self, plaintext: bytes, nonce: bytes = None) -> (bytes, bytes):
"""
Шифрует plaintext. Возвращает (ciphertext, nonce).
Если nonce не передан — генерирует случайный (16 байт).
"""
if nonce is None:
nonce = os.urandom(16)
keystream = self._generate_keystream(nonce, len(plaintext))
ciphertext = bytes(p ^ k for p, k in zip(plaintext, keystream))
return ciphertext, nonce
def decrypt(self, ciphertext: bytes, nonce: bytes) -> bytes:
"""Расшифровывает ciphertext с использованием nonce."""
keystream = self._generate_keystream(nonce, len(ciphertext))
return bytes(c ^ k for c, k in zip(ciphertext, keystream))
# ===== Пример использования =====
if __name__ == "__main__":
# Генерация ключа (сохранить в секрете!)
key = os.urandom(32)
cipher = QuantumResistantStreamCipher(key)
plaintext = b"Secret data: 42. " + token_bytes(16)
print("Original:", plaintext)
# Шифрование (автоматический nonce)
ciphertext, nonce = cipher.encrypt(plaintext)
print("Ciphertext:", ciphertext.hex())
print("Nonce:", nonce.hex())
# Расшифровка
decrypted = cipher.decrypt(ciphertext, nonce)
print("Decrypted:", decrypted)
assert decrypted == plaintext, "Ошибка: потеря данных!"
P.S.: Скрипт работает нормально
Изменено: ИИ говорит что взлом на суперкомпьютер е будет идти больше чем возраст вселенной.