js-libp2p-noise/src/encoder.ts

28 lines
809 B
TypeScript
Raw Normal View History

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);
2019-12-24 17:27:55 +01:00
return target.writeUInt16BE(value, offset);
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
export function encodeMessageBuffer(message: MessageBuffer): bytes {
return Buffer.concat([message.ne, message.ns, message.ciphertext]);
}
export function decodeMessageBuffer(message: bytes): MessageBuffer {
return {
ne: message.slice(0, 32),
ns: message.slice(32, 64),
ciphertext: message.slice(64, message.length),
}
}