I'm trying to hash a string. But what is the alternative for function TextEncoder in IE11 and Safari?
var string = "foobar";
window.crypto.subtle.digest(
{ "name": "SHA-256" },
new TextEncoder("utf-8").encode(string)).then(function (hash)
{
console.log(hex(hash)); // 'c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2'
}
);
var string = "foobar";
var buffer = new TextEncoder("utf-8").encode(string); // Uint8Array (ArrayBuffer)
var string = new TextDecoder("utf-8").decode(buffer); // string
console.log("buffer", buffer);
console.log("string '" + string + "'");
hex is a function I got from mozilla
https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
Edit: I just ended up using the SHA256 routine from http://www.movable-type.co.uk/scripts/sha256.html because I didn't need high performance, and the code is short and sweet and the same code path is used everywhere. The crypto.subtle API turned out to have too many corner cases where it failed for me (I had problems on some mobile devices, apart from the Chrome issue linked below that caused me grief, and I needed to support older browsers too).
I wrote this function for IE11 which worked for me (although hardly tested):
Be aware there are other problems because IE11 doesn't have promises, and
msCrypto.subtle.digest()
is synchronous. The following might work for you, although you should fix the hacks (it needs work to make it robust and to use a Promise polyfill):Also be aware of this Chrome issue which you can use the regexp
/^https:|^file:|^http:\/\/localhost|^http:\/\/127.0.0.1/.test(location.protocol)
to test for.