js-libp2p-noise/src/encoder.ts

67 lines
1.8 KiB
TypeScript
Raw Normal View History

2020-06-19 12:49:40 +02:00
import { Buffer } from 'buffer'
import { bytes } from './@types/basic'
import { MessageBuffer } from './@types/handshake'
2019-12-03 15:15:46 +01:00
2020-06-19 13:06:31 +02:00
export const uint16BEEncode = (value: number, target: bytes, offset: number): bytes => {
2020-06-19 12:49:40 +02:00
target = target || Buffer.allocUnsafe(2)
target.writeUInt16BE(value, offset)
return target
}
uint16BEEncode.bytes = 2
2019-12-03 15:15:46 +01:00
2020-06-19 13:06:31 +02:00
export const uint16BEDecode = (data: bytes): number => {
2020-06-19 12:49:40 +02:00
if (data.length < 2) throw RangeError('Could not decode int16BE')
return data.readUInt16BE(0)
}
uint16BEDecode.bytes = 2
2019-12-03 15:15:46 +01:00
// Note: IK and XX encoder usage is opposite (XX uses in stages encode0 where IK uses encode1)
2020-06-19 12:49:40 +02:00
export function encode0 (message: MessageBuffer): bytes {
return Buffer.concat([message.ne, message.ciphertext])
2020-01-07 10:29:40 +01:00
}
2020-06-19 12:49:40 +02:00
export function encode1 (message: MessageBuffer): bytes {
return Buffer.concat([message.ne, message.ns, message.ciphertext])
2019-12-03 15:15:46 +01:00
}
2020-06-19 12:49:40 +02:00
export function encode2 (message: MessageBuffer): bytes {
return Buffer.concat([message.ns, message.ciphertext])
}
2020-06-19 12:49:40 +02:00
export function decode0 (input: bytes): MessageBuffer {
2020-01-07 10:29:40 +01:00
if (input.length < 32) {
2020-06-19 12:49:40 +02:00
throw new Error('Cannot decode stage 0 MessageBuffer: length less than 32 bytes.')
2020-01-07 10:29:40 +01:00
}
return {
ne: input.slice(0, 32),
ciphertext: input.slice(32, input.length),
2020-06-19 12:49:40 +02:00
ns: Buffer.alloc(0)
2020-01-07 10:29:40 +01:00
}
}
2020-06-19 12:49:40 +02:00
export function decode1 (input: bytes): MessageBuffer {
2020-02-17 12:11:55 +01:00
if (input.length < 80) {
2020-06-19 12:49:40 +02:00
throw new Error('Cannot decode stage 1 MessageBuffer: length less than 80 bytes.')
2020-01-07 10:29:40 +01:00
}
2019-12-03 15:15:46 +01:00
return {
2020-01-07 10:29:40 +01:00
ne: input.slice(0, 32),
2020-02-17 12:11:55 +01:00
ns: input.slice(32, 80),
2020-06-19 12:49:40 +02:00
ciphertext: input.slice(80, input.length)
2019-12-03 15:15:46 +01:00
}
}
2020-06-19 12:49:40 +02:00
export function decode2 (input: bytes): MessageBuffer {
if (input.length < 48) {
2020-06-19 12:49:40 +02:00
throw new Error('Cannot decode stage 2 MessageBuffer: length less than 48 bytes.')
}
return {
ne: Buffer.alloc(0),
ns: input.slice(0, 48),
2020-06-19 12:49:40 +02:00
ciphertext: input.slice(48, input.length)
}
}