js-libp2p-noise/src/crypto.ts

50 lines
1.7 KiB
TypeScript
Raw Normal View History

2020-06-19 12:49:40 +02:00
import { Buffer } from 'buffer'
import { IHandshake } from './@types/handshake-interface'
import { NOISE_MSG_MAX_LENGTH_BYTES, NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG } from './constants'
2019-11-12 14:02:59 +01:00
2020-01-11 20:27:26 +01:00
interface IReturnEncryptionWrapper {
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
2020-06-19 12:49:40 +02:00
export function encryptStream (handshake: IHandshake): IReturnEncryptionWrapper {
2019-11-25 13:09:40 +01:00
return async function * (source) {
for await (const chunk of source) {
2020-06-19 12:49:40 +02:00
const chunkBuffer = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.length)
2019-12-24 13:46:50 +01:00
2020-02-17 12:11:55 +01:00
for (let i = 0; i < chunkBuffer.length; i += NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG) {
2020-06-19 12:49:40 +02:00
let end = i + NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG
2019-12-24 13:46:50 +01:00
if (end > chunkBuffer.length) {
2020-06-19 12:49:40 +02:00
end = chunkBuffer.length
2019-12-24 13:46:50 +01:00
}
2020-06-19 12:49:40 +02:00
const data = handshake.encrypt(chunkBuffer.slice(i, end), handshake.session)
yield data
2019-12-24 13:46:50 +01:00
}
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-06-19 12:49:40 +02:00
export function decryptStream (handshake: IHandshake): IReturnEncryptionWrapper {
2019-11-25 13:09:40 +01:00
return async function * (source) {
for await (const chunk of source) {
2020-06-19 12:49:40 +02:00
const chunkBuffer = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.length)
2019-12-24 20:36:16 +01:00
2020-02-17 12:11:55 +01:00
for (let i = 0; i < chunkBuffer.length; i += NOISE_MSG_MAX_LENGTH_BYTES) {
2020-06-19 12:49:40 +02:00
let end = i + NOISE_MSG_MAX_LENGTH_BYTES
2019-12-24 20:36:16 +01:00
if (end > chunkBuffer.length) {
2020-06-19 12:49:40 +02:00
end = chunkBuffer.length
2019-12-24 20:36:16 +01:00
}
2020-06-19 12:49:40 +02:00
const chunk = chunkBuffer.slice(i, end)
const { plaintext: decrypted, valid } = await handshake.decrypt(chunk, handshake.session)
if (!valid) {
throw new Error('Failed to validate decrypted chunk')
2020-03-01 19:05:53 +01:00
}
2020-06-19 12:49:40 +02:00
yield decrypted
2019-12-24 20:36:16 +01:00
}
2019-11-25 13:09:40 +01:00
}
}
2019-11-12 14:02:59 +01:00
}