Skip to content

Instantly share code, notes, and snippets.

@SourceBoy
Last active April 25, 2022 02:57
Show Gist options
  • Save SourceBoy/f6fe895b3abf3f47c11361a6bf80a3d2 to your computer and use it in GitHub Desktop.
Save SourceBoy/f6fe895b3abf3f47c11361a6bf80a3d2 to your computer and use it in GitHub Desktop.
Web Crypto Hashing
/**
* sha256
* @param {string} [input='']
* @param {string} [algorithm='SHA-256']
* @returns {Promise<string>}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest}
* @author SourceBoy
* @license MIT
*/
async function sha256(input = '', algorithm = 'SHA-256') {
const encoder = new TextEncoder();
const encoded = encoder.encode(input);
const digest = await crypto.subtle.digest(algorithm, encoded);
const uints = new Uint8Array(digest);
const parts = Array.from(uints).map(b => b.toString(16));
return parts.join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment