如何使用javascript将UTF-8字符串转换为Latin1编码的字符串?
这是我想要做的:
并使用以下代码将其传递给cryptoJS进行哈希计算:
cryptosha256 = CryptoJS.algo.SHA256.create();
cryptosha256.update(text);
hash = cryptosha256.finalize();
Run Code Online (Sandbox Code Playgroud)这一切都适用于文本文件.使用代码散列非文本文件(image/.wmv文件)时出现问题.我在另一篇博客中看到,CryptoJS作者要求使用Latin1格式而不是UTF-8发送字节,这就是我被困住的地方.
不确定,如何在javascript中使用arraybuffer中的Latin1格式生成字节(或字符串)?
$('#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();
}
Run Code Online (Sandbox Code Playgroud)