Skip to content

Instantly share code, notes, and snippets.

@drhayes
Created October 27, 2016 19:28
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 drhayes/d71b2c4a3d07eb0776e5db7783df0802 to your computer and use it in GitHub Desktop.
Save drhayes/d71b2c4a3d07eb0776e5db7783df0802 to your computer and use it in GitHub Desktop.
SHA-1 a string in the browser
function sha1(str) {
function hex(buffer) {
const hexCodes = [];
const view = new DataView(buffer);
for (let i = 0; i < view.byteLength; i += 4) {
// Using getUint32 reduces the number of iterations needed (we process 4 bytes each time)
const value = view.getUint32(i)
// toString(16) will give the hex representation of the number without padding
const stringValue = value.toString(16)
// We use concatenation and slice for padding.
hexCodes.push(`00000000${stringValue}`.slice(-8))
}
// Join all the hex strings into one
return hexCodes.join('');
}
// We transform the string into an arraybuffer.
const buffer = new TextEncoder('utf-8').encode(str);
return crypto.subtle.digest('SHA-1', buffer).then(hash => hex(hash));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment