Created
October 27, 2016 19:28
-
-
Save drhayes/d71b2c4a3d07eb0776e5db7783df0802 to your computer and use it in GitHub Desktop.
SHA-1 a string in the browser
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 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