CyberChef/src/js/operations/Endian.js

95 lines
1.9 KiB
JavaScript
Raw Normal View History

2016-11-28 10:42:58 +00:00
/**
* Endian operations.
*
* @author n1474335 [n1474335@gmail.com]
* @copyright Crown Copyright 2016
* @license Apache-2.0
*
* @namespace
*/
2016-11-29 00:22:34 +00:00
const Endian = {
2016-11-28 10:42:58 +00:00
/**
* @constant
* @default
*/
2016-11-29 00:22:34 +00:00
DATA_FORMAT: ['Hex', 'Raw'],
2016-11-28 10:42:58 +00:00
/**
* @constant
* @default
*/
2016-11-29 00:22:34 +00:00
WORD_LENGTH: 4,
2016-11-28 10:42:58 +00:00
/**
* @constant
* @default
*/
2016-11-29 00:22:34 +00:00
PAD_INCOMPLETE_WORDS: true,
2016-11-28 10:42:58 +00:00
/**
* Swap endianness operation.
*
* @param {string} input
* @param {Object[]} args
* @returns {string}
*/
2016-11-29 00:22:34 +00:00
run_swap_endianness(input, args) {
let data_format = args[0],
word_length = args[1],
pad_incomplete_words = args[2],
data = [],
result = [],
words = [],
i = 0,
j = 0;
if (word_length <= 0) {
return 'Word length must be greater than 0';
}
2016-11-28 10:42:58 +00:00
// Convert input to raw data based on specified data format
2016-11-29 00:22:34 +00:00
switch (data_format) {
case 'Hex':
data = Utils.from_hex(input);
break;
case 'Raw':
data = Utils.str_to_byte_array(input);
break;
default:
data = input;
}
2016-11-28 10:42:58 +00:00
// Split up into words
2016-11-29 00:22:34 +00:00
for (i = 0; i < data.length; i += word_length) {
const word = data.slice(i, i + word_length);
2016-11-28 10:42:58 +00:00
// Pad word if too short
2016-11-29 00:22:34 +00:00
if (pad_incomplete_words && word.length < word_length) {
for (j = word.length; j < word_length; j++) {
word.push(0);
2016-11-28 10:42:58 +00:00
}
2016-11-29 00:22:34 +00:00
}
words.push(word);
}
2016-11-28 10:42:58 +00:00
// Swap endianness and flatten
2016-11-29 00:22:34 +00:00
for (i = 0; i < words.length; i++) {
j = words[i].length;
while (j--) {
result.push(words[i][j]);
}
}
2016-11-28 10:42:58 +00:00
// Convert data back to specified data format
2016-11-29 00:22:34 +00:00
switch (data_format) {
case 'Hex':
return Utils.to_hex(result);
case 'Raw':
return Utils.byte_array_to_utf8(result);
default:
return result;
}
},
2016-11-28 10:42:58 +00:00
};