js-libp2p-noise/src/crypto.ts

31 lines
911 B
TypeScript
Raw Normal View History

2019-11-20 13:23:36 +01:00
import { Duplex } from "it-pair";
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 10:48:19 +01:00
(source: Iterable<Uint8Array>): any;
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 12:53:27 +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
}