CyberChef/src/core/lib/TLVParser.mjs

79 lines
1.6 KiB
JavaScript
Raw Normal View History

2018-08-27 02:17:06 +02:00
/**
2018-10-10 15:56:20 +02:00
* Parser for Type-length-value data.
*
2018-08-27 02:17:06 +02:00
* @author gchq77703 []
2018-10-10 15:56:20 +02:00
* @author n1474335 [n1474335@gmail.com]
2018-08-27 02:17:06 +02:00
* @copyright Crown Copyright 2018
* @license Apache-2.0
*/
const defaults = {
location: 0,
bytesInLength: 1,
basicEncodingRules: false
};
/**
2018-10-10 15:56:20 +02:00
* TLVParser library
2018-08-27 02:17:06 +02:00
*/
2018-10-10 15:56:20 +02:00
export default class TLVParser {
2018-08-27 02:17:06 +02:00
/**
2018-10-10 15:56:20 +02:00
* TLVParser constructor
*
* @param {byteArray|Uint8Array} input
2018-10-10 15:56:20 +02:00
* @param {Object} options
2018-08-27 02:17:06 +02:00
*/
constructor(input, options) {
this.input = input;
Object.assign(this, defaults, options);
}
/**
2018-10-10 15:56:20 +02:00
* @returns {number}
2018-08-27 02:17:06 +02:00
*/
getLength() {
if (this.basicEncodingRules) {
const bit = this.input[this.location];
if (bit & 0x80) {
this.bytesInLength = bit & ~0x80;
} else {
this.location++;
return bit & ~0x80;
}
}
let length = 0;
for (let i = 0; i < this.bytesInLength; i++) {
length += this.input[this.location] * Math.pow(Math.pow(2, 8), i);
this.location++;
}
return length;
}
/**
2018-10-10 15:56:20 +02:00
* @param {number} length
* @returns {number[]}
2018-08-27 02:17:06 +02:00
*/
getValue(length) {
const value = [];
for (let i = 0; i < length; i++) {
2018-10-10 15:56:20 +02:00
if (this.location > this.input.length) return value;
2018-08-27 02:17:06 +02:00
value.push(this.input[this.location]);
this.location++;
}
return value;
}
/**
2018-10-10 15:56:20 +02:00
* @returns {boolean}
2018-08-27 02:17:06 +02:00
*/
atEnd() {
return this.input.length <= this.location;
}
}