Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@7c
Created November 29, 2018 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 7c/7b969f5ed817e7332e3813e23adc2aa5 to your computer and use it in GitHub Desktop.
Save 7c/7b969f5ed817e7332e3813e23adc2aa5 to your computer and use it in GitHub Desktop.
Browser implementation of sha512
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);
});
@Illizion
Copy link

Illizion commented Dec 4, 2018

crypto is a native node module iirc. I'll give it another check, but i don't think this is browser-compatible

@Illizion
Copy link

Illizion commented Dec 4, 2018

well, i guess i was wrong 🤣 sorry about that i was wrong

@Illizion
Copy link

Illizion commented Dec 4, 2018

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