Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Created March 6, 2022 02:54
Show Gist options
  • Save dfkaye/84feac3688b110e698ad3b81713414a9 to your computer and use it in GitHub Desktop.
Save dfkaye/84feac3688b110e698ad3b81713414a9 to your computer and use it in GitHub Desktop.
Use crypto subtle digest to create hash hex string
// 5 March 2022
// Using window.crypto.subtle.digest()
// @param "sha-256" or other algorithm
// @param DataView with ArrayBuffer or just ArrayBuffer
// Not my own.
// Copy+paste+modified from
// https://stackoverflow.com/a/68545495
/**
* @function Hex converts a Uint8Array to a hex string using the supplied algorithm.
* @param {"SHA-1"|"SHA-256"|"SHA-384"|"SHA-512"} algorithm https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
* @param Uint8Array msgUint8
* @returns Promise hexString
*/
async function Hex(algorithm, msgUint8) {
// https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest#converting_a_digest_to_a_hex_string
var hashBuffer = await crypto.subtle.digest(algorithm, msgUint8)
var hashArray = Array.from(new Uint8Array(hashBuffer))
// convert bytes to hex string
return hashArray.map(function(b) {
return b.toString(16).padStart(2, '0')
}).join('');
}
/**
* @function Hash passes data to the Hex function and returns a hex string using the supplied algorithm. Data may be a string or a Blob.
* @param {"SHA-1"|"SHA-256"|"SHA-384"|"SHA-512"} algorithm https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
* @param {string|Blob} data
* @returns Promise hexString
*/
async function Hash(algorithm, data) {
if (data instanceof Blob) {
var arrayBuffer = await data.arrayBuffer()
var msgUint8 = new Uint8Array(arrayBuffer)
return await Hex(msgUint8)
}
var encoder = new TextEncoder()
var msgUint8 = encoder.encode(data)
return await Hex(algorithm, msgUint8)
}
// Create a source
var source = {
name: "test",
value: "test"
}
// Convert to a string
var json = JSON.stringify(source)
var hash = await Hash('sha-256', json)
var hash2 = await Hash('sha-256', json)
console.log(hash)
console.log(hash2)
// 6287804eacecfa191e5761dfcbfbeb181bf20e52248fb71807f3801beba1a4f7
console.warn(hash === hash2)
// true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment