how do I convert a UTF-8 string to Latin1 encoded string using javascript?
Here is what I am trying to do:
- I get a file, split that in chunks by reading as arraybuffer
- then, I parse the arraybuffer as string
and passing it to cryptoJS for hash computation using following code:
cryptosha256 = CryptoJS.algo.SHA256.create(); cryptosha256.update(text); hash = cryptosha256.finalize();
It all works well for a text file. I get problems when using the code for hashing a non-text files (image/.wmv files). I saw in another blog and there the CryptoJS author requires the bytes to be sent using Latin1 format instead of UTF-8 and that's where I am stuck.
Not sure, how can I generate the bytes (or strings) using Latin1 format from arraybuffer in javascript?
$('#btnHash').click(function () {
var fr = new FileReader(),
file = document.getElementById("fileName").files[0];
fr.onload = function (e) {
calcHash(e.target.result, file);
};
fr.readAsArrayBuffer(file);
});
function calcHash(dataArray, file) {
cryptosha256 = CryptoJS.algo.SHA256.create();
text = CryptoJS.enc.Latin1.parse(dataArray);
cryptosha256.update(text);
hash = cryptosha256.finalize();
}
evt.target.result
contains the correct value? Please update your question with the whole code snippet. – FlosireadAsBinaryString
too. That still gets me undefined as `hash' value... – MarvelousCryptoJS.enc.Latin1.parse(evt.target.result)
to get the proper SHA1 hash finally worked for me. It seems when reading binary data, the Latin1 parsing is needed. – Groyne