2019-11-25 13:09:40 +01:00
|
|
|
import { Handshake } from "./handshake";
|
2019-12-02 10:48:19 +01:00
|
|
|
import { Buffer } from "buffer";
|
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-11-25 13:09:40 +01:00
|
|
|
// Returns generator that encrypts payload from the user
|
2019-12-02 15:28:59 +01:00
|
|
|
export function encryptStream(handshake: Handshake): ReturnEncryptionWrapper {
|
2019-11-25 13:09:40 +01:00
|
|
|
return async function * (source) {
|
|
|
|
for await (const chunk of source) {
|
2019-12-02 10:48:19 +01:00
|
|
|
const chunkBuffer = Buffer.from(chunk);
|
|
|
|
const data = await handshake.encrypt(chunkBuffer, handshake.session);
|
2019-11-25 13:09:40 +01:00
|
|
|
yield data;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-11-12 14:02:59 +01:00
|
|
|
|
|
|
|
|
2019-11-25 13:09:40 +01:00
|
|
|
// Decrypt received payload to the user
|
2019-11-29 16:23:24 +01:00
|
|
|
export function decryptStream(handshake: Handshake): ReturnEncryptionWrapper {
|
2019-11-25 13:09:40 +01:00
|
|
|
return async function * (source) {
|
|
|
|
for await (const chunk of source) {
|
2019-12-02 10:48:19 +01:00
|
|
|
const chunkBuffer = Buffer.from(chunk);
|
|
|
|
const decrypted = await handshake.decrypt(chunkBuffer, handshake.session);
|
2019-11-25 13:09:40 +01:00
|
|
|
yield decrypted
|
|
|
|
}
|
|
|
|
}
|
2019-11-12 14:02:59 +01:00
|
|
|
}
|