mirror of
https://github.com/fluencelabs/js-libp2p-noise
synced 2025-04-25 18:32:22 +00:00
Encrypt stream in chunks
This commit is contained in:
parent
5167df18a5
commit
128aba164d
@ -1,20 +1,33 @@
|
|||||||
import { Handshake } from "./handshake";
|
|
||||||
import { Buffer } from "buffer";
|
import { Buffer } from "buffer";
|
||||||
|
import { Handshake } from "./handshake";
|
||||||
|
|
||||||
interface ReturnEncryptionWrapper {
|
interface ReturnEncryptionWrapper {
|
||||||
(source: Iterable<Uint8Array>): AsyncIterableIterator<Uint8Array>;
|
(source: Iterable<Uint8Array>): AsyncIterableIterator<Uint8Array>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const maxPlaintextLength = 65519;
|
||||||
|
|
||||||
|
|
||||||
// Returns generator that encrypts payload from the user
|
// Returns generator that encrypts payload from the user
|
||||||
export function encryptStream(handshake: Handshake): ReturnEncryptionWrapper {
|
export function encryptStream(handshake: Handshake): ReturnEncryptionWrapper {
|
||||||
return async function * (source) {
|
return async function * (source) {
|
||||||
for await (const chunk of source) {
|
for await (const chunk of source) {
|
||||||
const chunkBuffer = Buffer.from(chunk);
|
const chunkBuffer = Buffer.from(chunk);
|
||||||
const data = await handshake.encrypt(chunkBuffer, handshake.session);
|
|
||||||
|
|
||||||
|
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;
|
yield data;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// Decrypt received payload to the user
|
// Decrypt received payload to the user
|
||||||
|
Loading…
x
Reference in New Issue
Block a user