'How to convert crypto.WordArray to Uint8Array?
The crypto-es library uses its own format for hash the WordArray
WordArray {
// The number of significant bytes in the words.
sigBytes: 16
// An array of 32-bit words.
words: [1013011610, 748842083, 565183709, -233379442]
}
How this WordArray
could be converted to Uint8Array
?
I need this because I have some converting hash to string that expect Uint8Array
as an input. And I can't use it with WordArray
hash.
Solution 1:[1]
This seems to work
function convert_word_array_to_uint8Array(wordArray: any) {
var len = wordArray.words.length,
u8_array = new Uint8Array(len << 2),
offset = 0, word, i
;
for (i=0; i<len; i++) {
word = wordArray.words[i];
u8_array[offset++] = word >> 24;
u8_array[offset++] = (word >> 16) & 0xff;
u8_array[offset++] = (word >> 8) & 0xff;
u8_array[offset++] = word & 0xff;
}
return u8_array;
}
Solution 2:[2]
var data = {
"sigBytes": 16,
"words": [1013011610, 748842083, 565183709, -233379442]
}
const dataArray = new Uint8Array(data.sigBytes);
for (let i = 0x0; i < data.sigBytes; i++) {
dataArray[i] = data.words[i >>> 0x2] >>> 0x18 - i % 0x4 * 0x8 & 0xff;
}
data = new Uint8Array(dataArray);
console.log(data);
/*
Uint8Array(16) [
60, 97, 84, 154, 44, 162,
108, 99, 33, 176, 4, 221,
242, 22, 233, 142
]
*/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Alex Craft |
Solution 2 | Nabi K.A.Z. |