Created
November 29, 2018 17:38
-
-
Save 7c/7b969f5ed817e7332e3813e23adc2aa5 to your computer and use it in GitHub Desktop.
Browser implementation of sha512
This file contains 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 hex(buffer) { | |
var hexCodes = []; | |
var view = new DataView(buffer); | |
for (var i = 0; i < view.byteLength; i += 4) { | |
// Using getUint32 reduces the number of iterations needed (we process 4 bytes each time) | |
var value = view.getUint32(i) | |
// toString(16) will give the hex representation of the number without padding | |
var stringValue = value.toString(16) | |
// We use concatenation and slice for padding | |
var padding = '00000000' | |
var paddedValue = (padding + stringValue).slice(-padding.length) | |
hexCodes.push(paddedValue); | |
} | |
// Join all the hex strings into one | |
return hexCodes.join(""); | |
} | |
function sha512(str) { | |
// We transform the string into an arraybuffer. | |
var buffer = new TextEncoder("utf-8").encode(str); | |
return crypto.subtle.digest("SHA-512", buffer).then(function (hash) { | |
return hex(hash); | |
}); | |
} | |
sha512("secret").then(function(digest) { | |
console.log(digest); | |
}); |
also i might write a decoder function, if you don't mind, and will send a link to that gist when done
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
crypto is a native node module iirc. I'll give it another check, but i don't think this is browser-compatible