js-libp2p-noise/src/crypto.ts

49 lines
1.5 KiB
TypeScript
Raw Normal View History

2019-12-02 10:48:19 +01:00
import { Buffer } from "buffer";
2020-01-07 13:34:45 +01:00
import {IHandshake} from "./@types/handshake-interface";
2019-11-12 14:02:59 +01:00
2019-11-28 17:53:27 +01:00
interface ReturnEncryptionWrapper {
2019-12-02 13:20:31 +01:00
(source: Iterable<Uint8Array>): AsyncIterableIterator<Uint8Array>;
2019-11-12 14:02:59 +01:00
}
2019-12-24 13:46:50 +01:00
const maxPlaintextLength = 65519;
2019-11-25 13:09:40 +01:00
// Returns generator that encrypts payload from the user
2020-01-07 13:34:45 +01:00
export function encryptStream(handshake: IHandshake): ReturnEncryptionWrapper {
2019-11-25 13:09:40 +01:00
return async function * (source) {
for await (const chunk of source) {
2019-12-27 13:15:06 +01:00
const chunkBuffer = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.length);
2019-12-24 13:46:50 +01:00
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;
}
2019-11-25 13:09:40 +01:00
}
}
}
2019-11-12 14:02:59 +01:00
2019-11-25 13:09:40 +01:00
// Decrypt received payload to the user
2020-01-07 13:34:45 +01:00
export function decryptStream(handshake: IHandshake): ReturnEncryptionWrapper {
2019-11-25 13:09:40 +01:00
return async function * (source) {
for await (const chunk of source) {
2019-12-27 13:15:06 +01:00
const chunkBuffer = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.length);
2019-12-24 20:36:16 +01:00
for (let i = 0; i < chunkBuffer.length; i += maxPlaintextLength) {
let end = i + maxPlaintextLength;
if (end > chunkBuffer.length) {
end = chunkBuffer.length;
}
const chunk = chunkBuffer.slice(i, end);
const decrypted = await handshake.decrypt(chunk, handshake.session);
yield decrypted;
}
2019-11-25 13:09:40 +01:00
}
}
2019-11-12 14:02:59 +01:00
}