Шифрование тест 2

This commit is contained in:
RoyceDa
2026-03-21 19:03:43 +02:00
parent 4df39cb83d
commit 0d70824d77

View File

@@ -21,24 +21,23 @@ function toUint8Array(input: KeyInput): Uint8Array {
}
function createFrameProcessor(key: Uint8Array) {
// Переиспользуемый nonce буфер — нет аллокаций на каждый фрейм
// Выделяем nonce один раз — переиспользуем на каждый фрейм
const nonce = new Uint8Array(sodium.crypto_stream_chacha20_NONCEBYTES); // 8 bytes
const nonceView = new DataView(nonce.buffer, 0, nonce.byteLength);
return function processFrame(data: ArrayBuffer): ArrayBuffer {
return function processFrame(data: ArrayBuffer, timestamp: number): ArrayBuffer {
const input = new Uint8Array(data);
// Обновляем nonce из длины и byteOffset фрейма — уникально и без аллокаций
nonce.fill(0);
new DataView(nonce.buffer).setUint32(0, input.byteLength ^ 0xdeadbeef, false);
new DataView(nonce.buffer).setUint32(4, input[0] ^ input[input.byteLength - 1], false);
// Безопасно записываем nonce через отдельный DataView
nonceView.setUint32(0, (timestamp >>> 0) & 0xffffffff, false);
nonceView.setUint32(4, ((timestamp / 0x100000000) >>> 0) & 0xffffffff, false);
// WASM ChaCha20 — синхронный, нативная скорость
const output = sodium.crypto_stream_chacha20_xor(input, nonce, key);
return output.buffer as ArrayBuffer;
};
}
function createTransform(processFrame: (data: ArrayBuffer) => ArrayBuffer) {
function createTransform(processFrame: (data: ArrayBuffer, timestamp: number) => ArrayBuffer) {
let frames = 0;
let slowFrames = 0;
let total = 0;
@@ -49,7 +48,9 @@ function createTransform(processFrame: (data: ArrayBuffer) => ArrayBuffer) {
const started = performance.now();
try {
frame.data = processFrame(frame.data);
// Передаём timestamp фрейма как nonce
const ts = typeof frame.timestamp === "number" ? frame.timestamp : 0;
frame.data = processFrame(frame.data, ts);
} catch (e) {
console.error("[E2EE] frame error:", e);
controller.enqueue(frame);