Skip to content

Commit

Permalink
Add prefix in encryptStream
Browse files Browse the repository at this point in the history
  • Loading branch information
dapplion committed Oct 14, 2022
1 parent 3bc8ed4 commit 646ef3c
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 4 deletions.
3 changes: 3 additions & 0 deletions src/crypto/streaming.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Transform } from 'it-stream-types'
import type { Uint8ArrayList } from 'uint8arraylist'
import type { IHandshake } from '../@types/handshake-interface.js'
import { NOISE_MSG_MAX_LENGTH_BYTES, NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG } from '../constants.js'
import { uint16BEEncode } from '../encoder.js'

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

const data = handshake.encrypt(chunk.subarray(i, end), handshake.session)

yield uint16BEEncode(data.byteLength)
yield data
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/encoder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { concat as uint8ArrayConcat } from 'uint8arrays/concat'
import type { Uint8ArrayList } from 'uint8arraylist'
import type { bytes } from './@types/basic.js'
import type { MessageBuffer } from './@types/handshake.js'
import type { LengthDecoderFunction, LengthEncoderFunction } from 'it-length-prefixed'
import type { LengthDecoderFunction } from 'it-length-prefixed'

const allocUnsafe = (len: number): Uint8Array => {
if (globalThis.Buffer) {
Expand All @@ -12,7 +12,7 @@ const allocUnsafe = (len: number): Uint8Array => {
return new Uint8Array(len)
}

export const uint16BEEncode: LengthEncoderFunction = (value: number) => {
export const uint16BEEncode = (value: number): Uint8Array => {
const target = allocUnsafe(2)
new DataView(target.buffer, target.byteOffset, target.byteLength).setUint16(0, value, false)
return target
Expand Down
3 changes: 1 addition & 2 deletions src/noise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,7 @@ export class Noise implements INoiseConnection {

await pipe(
secure, // write to wrapper
encryptStream(handshake), // data is encrypted
encode({ lengthEncoder: uint16BEEncode }), // prefix with message length
encryptStream(handshake), // encrypt data + prefix with message length
network, // send to the remote peer
decode({ lengthDecoder: uint16BEDecode }), // read message length prefix
decryptStream(handshake), // decrypt the incoming data
Expand Down

0 comments on commit 646ef3c

Please sign in to comment.