Skip to content

Commit 646ef3c

Browse files
committed
Add prefix in encryptStream
1 parent 3bc8ed4 commit 646ef3c

3 files changed

Lines changed: 6 additions & 4 deletions

File tree

src/crypto/streaming.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type { Transform } from 'it-stream-types'
22
import type { Uint8ArrayList } from 'uint8arraylist'
33
import type { IHandshake } from '../@types/handshake-interface.js'
44
import { NOISE_MSG_MAX_LENGTH_BYTES, NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG } from '../constants.js'
5+
import { uint16BEEncode } from '../encoder.js'
56

67
// Returns generator that encrypts payload from the user
78
export function encryptStream (handshake: IHandshake): Transform<Uint8Array> {
@@ -14,6 +15,8 @@ export function encryptStream (handshake: IHandshake): Transform<Uint8Array> {
1415
}
1516

1617
const data = handshake.encrypt(chunk.subarray(i, end), handshake.session)
18+
19+
yield uint16BEEncode(data.byteLength)
1720
yield data
1821
}
1922
}

src/encoder.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { concat as uint8ArrayConcat } from 'uint8arrays/concat'
22
import type { Uint8ArrayList } from 'uint8arraylist'
33
import type { bytes } from './@types/basic.js'
44
import type { MessageBuffer } from './@types/handshake.js'
5-
import type { LengthDecoderFunction, LengthEncoderFunction } from 'it-length-prefixed'
5+
import type { LengthDecoderFunction } from 'it-length-prefixed'
66

77
const allocUnsafe = (len: number): Uint8Array => {
88
if (globalThis.Buffer) {
@@ -12,7 +12,7 @@ const allocUnsafe = (len: number): Uint8Array => {
1212
return new Uint8Array(len)
1313
}
1414

15-
export const uint16BEEncode: LengthEncoderFunction = (value: number) => {
15+
export const uint16BEEncode = (value: number): Uint8Array => {
1616
const target = allocUnsafe(2)
1717
new DataView(target.buffer, target.byteOffset, target.byteLength).setUint16(0, value, false)
1818
return target

src/noise.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -165,8 +165,7 @@ export class Noise implements INoiseConnection {
165165

166166
await pipe(
167167
secure, // write to wrapper
168-
encryptStream(handshake), // data is encrypted
169-
encode({ lengthEncoder: uint16BEEncode }), // prefix with message length
168+
encryptStream(handshake), // encrypt data + prefix with message length
170169
network, // send to the remote peer
171170
decode({ lengthDecoder: uint16BEDecode }), // read message length prefix
172171
decryptStream(handshake), // decrypt the incoming data

0 commit comments

Comments
 (0)