Last active
January 19, 2021 23:39
-
-
Save antoninkriz/b86fe660a477c4aff9ab55dca351a3eb to your computer and use it in GitHub Desktop.
Hashing strings in JS using the built-in SubtleCrypto library
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
const stringToUTF8Array = str => { | |
const utf8 = []; | |
for (let i = 0; i < str.length; i++) { | |
let charCode = str.charCodeAt(i); | |
if (charCode < 0x80) utf8.push(charCode); | |
else if (charCode < 0x800) { | |
utf8.push(0xc0 | (charCode >> 6), | |
0x80 | (charCode & 0x3f)); | |
} else if (charCode < 0xd800 || charCode >= 0xe000) { | |
utf8.push(0xe0 | (charCode >> 12), | |
0x80 | ((charCode >> 6) & 0x3f), | |
0x80 | (charCode & 0x3f)); | |
} else { | |
i++; | |
charCode = 0x10000 + (((charCode & 0x3ff) << 10) | |
| (str.charCodeAt(i) & 0x3ff)) | |
utf8.push(0xf0 | (charCode >> 18), | |
0x80 | ((charCode >> 12) & 0x3f), | |
0x80 | ((charCode >> 6) & 0x3f), | |
0x80 | (charCode & 0x3f)); | |
} | |
} | |
return new Uint8Array(utf8); | |
} | |
const binaryArrayToBase64 = async bin => { | |
if (!bin || bin.length <= 0) | |
return ''; | |
const blob = new Blob([bin], { type: 'application/octet-binary' }); | |
const reader = new FileReader(); | |
const promise = new Promise(resolve => { | |
reader.onloadend = () => { | |
resolve(reader.result ? reader.result.substr(reader.result.indexOf(',') + 1) : ''); | |
}; | |
}); | |
reader.readAsDataURL(blob); | |
return await promise; | |
} | |
// Password | |
const password = "ThisIsSafe123"; | |
// Get UTF8 bytes from the string password | |
const utfBytesPassword = stringToUTF8Array(password); | |
// Generate SHA-512 hash | |
const sha512Hash = await crypto.subtle.digest('SHA-512', utfBytesPassword); | |
// Base64 SHA512 string | |
const encodedPasswordHash = await binaryArrayToBase64(sha512Hash); | |
console.log(encodedPasswordHash); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment