Created
April 27, 2017 15:23
-
-
Save harmoniemand/7b9c7e77d5f3800b3068fd4ba49fb476 to your computer and use it in GitHub Desktop.
Create SHA256 Hash in IE and Chrome (others not tested)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function convertArrayBufferToHexaDecimal(buffer) { | |
var data_view = new DataView(buffer); | |
var iii, len, hex = "", c; | |
for ((iii = 0), (len = data_view.byteLength); iii < len; iii += 1) { | |
c = data_view.getUint8(iii).toString(16); | |
if (c.length < 2) c = "0" + c; | |
hex += c; | |
} | |
return hex; | |
} | |
function convertStringToArrayBufferView(str) { | |
var bytes = new Uint8Array(str.length); | |
for (var iii = 0; iii < str.length; iii++) | |
bytes[iii] = str.charCodeAt(iii); | |
return bytes; | |
} | |
function crypt(data) { | |
var crypto = window.crypto || window.msCrypto; | |
if (crypto.subtle) { | |
console.log("Cryptography API Supported"); | |
var crypt = crypto.subtle.digest( | |
{ name: "SHA-256" }, | |
convertStringToArrayBufferView(data) | |
); | |
if (typeof crypt.then == "function") { | |
crypt.then(function(result) { | |
result = convertArrayBufferToHexaDecimal(result); | |
console.log("hashed"); | |
console.log(result); | |
}); | |
} else { | |
var result = convertArrayBufferToHexaDecimal(crypt.result); | |
console.log("hashed"); | |
console.log(result); | |
} | |
} else { | |
console.log("Cryptography API not Supported"); | |
} | |
}; | |
crypt("supersavetohash"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment