Skip to content

Instantly share code, notes, and snippets.

@tscholl2
Created July 13, 2020 13:03
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 tscholl2/fb72622049b1cc8f12f00edd1b2a48f8 to your computer and use it in GitHub Desktop.
Save tscholl2/fb72622049b1cc8f12f00edd1b2a48f8 to your computer and use it in GitHub Desktop.
/**
* Given a sting s, return the SHA-256 digest of s
* (encoded as a UTF-16-LE byte array) in hex form.
* @param {string} s
* @returns {string}
*
* python -c 'import hashlib; print(hashlib.sha256("a🐦".encode("utf-16-le")).hexdigest())'
* 49f1ecba591ec4ae7a049570bd21b97dc77d42659f3fbe70a34a8f02ebacee17
*
* python -c 'import hashlib; print(hashlib.sha256("$€𐐷𤭢".encode("utf-16-le")).hexdigest())'
* 38f4744c36668c13a88e34c4c270292615d55a07fa5d4af9a8fc2364c34273be
*/
async function sha256(s) {
return Array.prototype.map.call(
new Uint8Array(
await window.crypto.subtle.digest(
"sha-256",
new Uint8Array([...s]
.map(x => x.codePointAt())
.map(y => y > 0xffff ? [((y - 0x10000) >> 10) | 0xD800, ((y - 0x10000) & 0x3ff) | 0xDC00] : y)
.flat().map(y => [y & 255, y >> 8]).flat())
)
),
x => x.toString(16).padStart(2, "0")
).join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment