From 128aba164d096fb86c608029480d14016ca22203 Mon Sep 17 00:00:00 2001 From: Belma Gutlic Date: Tue, 24 Dec 2019 13:46:50 +0100 Subject: [PATCH] Encrypt stream in chunks --- src/crypto.ts | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/crypto.ts b/src/crypto.ts index 5d583d2..81b1121 100644 --- a/src/crypto.ts +++ b/src/crypto.ts @@ -1,22 +1,35 @@ -import { Handshake } from "./handshake"; import { Buffer } from "buffer"; +import { Handshake } from "./handshake"; interface ReturnEncryptionWrapper { (source: Iterable): AsyncIterableIterator; } +const maxPlaintextLength = 65519; + + // Returns generator that encrypts payload from the user export function encryptStream(handshake: Handshake): ReturnEncryptionWrapper { return async function * (source) { for await (const chunk of source) { const chunkBuffer = Buffer.from(chunk); - const data = await handshake.encrypt(chunkBuffer, handshake.session); - yield data; + + + for (let i = 0; i < chunkBuffer.length; i += maxPlaintextLength) { + let end = i + maxPlaintextLength; + if (end > chunkBuffer.length) { + end = chunkBuffer.length; + } + + const data = handshake.encrypt(chunkBuffer.slice(i, end), handshake.session); + yield data; + } } } } + // Decrypt received payload to the user export function decryptStream(handshake: Handshake): ReturnEncryptionWrapper { return async function * (source) {