CyberChef/src/core/operations/Endian.js

100 lines
2.2 KiB
JavaScript
Raw Normal View History

import Utils from "../Utils.js";
2016-11-28 11:42:58 +01:00
/**
* Endian operations.
*
* @author n1474335 [n1474335@gmail.com]
* @copyright Crown Copyright 2016
* @license Apache-2.0
*
* @namespace
*/
const Endian = {
2017-02-09 16:09:33 +01:00
2016-11-28 11:42:58 +01:00
/**
* @constant
* @default
*/
DATA_FORMAT: ["Hex", "Raw"],
/**
* @constant
* @default
*/
WORD_LENGTH: 4,
/**
* @constant
* @default
*/
PAD_INCOMPLETE_WORDS: true,
2017-02-09 16:09:33 +01:00
2016-11-28 11:42:58 +01:00
/**
* Swap endianness operation.
*
* @param {string} input
* @param {Object[]} args
* @returns {string}
*/
runSwapEndianness: function(input, args) {
2017-04-13 19:08:50 +02:00
let dataFormat = args[0],
wordLength = args[1],
padIncompleteWords = args[2],
2016-11-28 11:42:58 +01:00
data = [],
result = [],
words = [],
i = 0,
j = 0;
2017-02-09 16:09:33 +01:00
if (wordLength <= 0) {
2016-11-28 11:42:58 +01:00
return "Word length must be greater than 0";
}
2017-02-09 16:09:33 +01:00
2016-11-28 11:42:58 +01:00
// Convert input to raw data based on specified data format
switch (dataFormat) {
2016-11-28 11:42:58 +01:00
case "Hex":
data = Utils.fromHex(input);
2016-11-28 11:42:58 +01:00
break;
case "Raw":
data = Utils.strToByteArray(input);
2016-11-28 11:42:58 +01:00
break;
default:
data = input;
}
2017-02-09 16:09:33 +01:00
2016-11-28 11:42:58 +01:00
// Split up into words
for (i = 0; i < data.length; i += wordLength) {
2017-04-13 19:08:50 +02:00
const word = data.slice(i, i + wordLength);
2017-02-09 16:09:33 +01:00
2016-11-28 11:42:58 +01:00
// Pad word if too short
if (padIncompleteWords && word.length < wordLength){
for (j = word.length; j < wordLength; j++) {
2016-11-28 11:42:58 +01:00
word.push(0);
}
}
2017-02-09 16:09:33 +01:00
2016-11-28 11:42:58 +01:00
words.push(word);
}
2017-02-09 16:09:33 +01:00
2016-11-28 11:42:58 +01:00
// Swap endianness and flatten
for (i = 0; i < words.length; i++) {
j = words[i].length;
while (j--) {
result.push(words[i][j]);
}
}
2017-02-09 16:09:33 +01:00
2016-11-28 11:42:58 +01:00
// Convert data back to specified data format
switch (dataFormat) {
2016-11-28 11:42:58 +01:00
case "Hex":
return Utils.toHex(result);
2016-11-28 11:42:58 +01:00
case "Raw":
return Utils.byteArrayToUtf8(result);
2016-11-28 11:42:58 +01:00
default:
return result;
}
},
2017-02-09 16:09:33 +01:00
2016-11-28 11:42:58 +01:00
};
export default Endian;