2019-12-03 15:15:46 +01:00
|
|
|
import {Buffer} from "buffer";
|
|
|
|
import {bytes} from "./@types/basic";
|
2019-12-24 20:54:45 +01:00
|
|
|
import {MessageBuffer} from "./@types/handshake";
|
2019-12-03 15:15:46 +01:00
|
|
|
|
2019-12-29 18:23:43 +01:00
|
|
|
export const uint16BEEncode = (value, target, offset) => {
|
2019-12-03 15:15:46 +01:00
|
|
|
target = target || Buffer.allocUnsafe(2);
|
2020-02-13 22:51:36 +01:00
|
|
|
target.writeUInt16BE(value, offset);
|
|
|
|
return target;
|
2019-12-03 15:15:46 +01:00
|
|
|
};
|
2019-12-29 18:23:43 +01:00
|
|
|
uint16BEEncode.bytes = 2;
|
2019-12-03 15:15:46 +01:00
|
|
|
|
2019-12-29 18:23:43 +01:00
|
|
|
export const uint16BEDecode = data => {
|
2019-12-03 15:15:46 +01:00
|
|
|
if (data.length < 2) throw RangeError('Could not decode int16BE');
|
2019-12-24 17:27:55 +01:00
|
|
|
return data.readUInt16BE(0);
|
2019-12-03 15:15:46 +01:00
|
|
|
};
|
2019-12-29 18:23:43 +01:00
|
|
|
uint16BEDecode.bytes = 2;
|
2019-12-03 15:15:46 +01:00
|
|
|
|
2020-01-17 23:40:51 +01:00
|
|
|
// Note: IK and XX encoder usage is opposite (XX uses in stages encode0 where IK uses encode1)
|
|
|
|
|
2020-01-07 10:29:40 +01:00
|
|
|
export function encode0(message: MessageBuffer): bytes {
|
|
|
|
return Buffer.concat([message.ne, message.ciphertext]);
|
|
|
|
}
|
|
|
|
|
|
|
|
export function encode1(message: MessageBuffer): bytes {
|
2019-12-03 15:15:46 +01:00
|
|
|
return Buffer.concat([message.ne, message.ns, message.ciphertext]);
|
|
|
|
}
|
|
|
|
|
2020-01-07 10:29:40 +01:00
|
|
|
export function decode0(input: bytes): MessageBuffer {
|
|
|
|
if (input.length < 32) {
|
|
|
|
throw new Error("Cannot decode stage 0 MessageBuffer: length less than 32 bytes.");
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
ne: input.slice(0, 32),
|
|
|
|
ciphertext: input.slice(32, input.length),
|
|
|
|
ns: Buffer.alloc(0),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function decode1(input: bytes): MessageBuffer {
|
2020-02-17 12:11:55 +01:00
|
|
|
if (input.length < 80) {
|
2020-01-07 10:29:40 +01:00
|
|
|
throw new Error("Cannot decode stage 0 MessageBuffer: length less than 96 bytes.");
|
|
|
|
}
|
|
|
|
|
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),
|
|
|
|
ciphertext: input.slice(80, input.length),
|
2019-12-03 15:15:46 +01:00
|
|
|
}
|
|
|
|
}
|