forked from ChainSafe/js-libp2p-noise
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrypto.ts
More file actions
43 lines (38 loc) · 1.44 KB
/
crypto.ts
File metadata and controls
43 lines (38 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { IHandshake } from './@types/handshake-interface'
import { NOISE_MSG_MAX_LENGTH_BYTES, NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG } from './constants'
interface IReturnEncryptionWrapper {
(source: Iterable<Uint8Array>): AsyncIterableIterator<Uint8Array>
}
// Returns generator that encrypts payload from the user
export function encryptStream (handshake: IHandshake): IReturnEncryptionWrapper {
return async function * (source) {
for await (const chunk of source) {
for (let i = 0; i < chunk.length; i += NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG) {
let end = i + NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG
if (end > chunk.length) {
end = chunk.length
}
const data = handshake.encrypt(chunk.slice(i, end), handshake.session)
yield data
}
}
}
}
// Decrypt received payload to the user
export function decryptStream (handshake: IHandshake): IReturnEncryptionWrapper {
return async function * (source) {
for await (const chunk of source) {
for (let i = 0; i < chunk.length; i += NOISE_MSG_MAX_LENGTH_BYTES) {
let end = i + NOISE_MSG_MAX_LENGTH_BYTES
if (end > chunk.length) {
end = chunk.length
}
const { plaintext: decrypted, valid } = await handshake.decrypt(chunk.slice(i, end), handshake.session)
if (!valid) {
throw new Error('Failed to validate decrypted chunk')
}
yield decrypted
}
}
}
}