Skip to content

Instantly share code, notes, and snippets.

@themikefuller
Created October 15, 2018 01:23
Show Gist options
  • Save themikefuller/c2f597d98aff6813714eb4ac8c65b2c3 to your computer and use it in GitHub Desktop.
Save themikefuller/c2f597d98aff6813714eb4ac8c65b2c3 to your computer and use it in GitHub Desktop.
SHA-1 and SHA-256 Hash Function in JavaScript using crypto.subtle.digest
async function SHA1(text) {
let data = new TextEncoder().encode(text.toString());
let digest = await crypto.subtle.digest("SHA-1",data);
return Array.from(new Uint8Array(digest)).map(val=>{return ('00' + val.toString(16)).slice(-2)}).join('');
}
async function SHA256(text) {
let data = new TextEncoder().encode(text.toString());
let digest = await crypto.subtle.digest("SHA-256",data);
return Array.from(new Uint8Array(digest)).map(val=>{return ('00' + val.toString(16)).slice(-2)}).join('');
}
@jacksonblankenship
Copy link

jacksonblankenship commented Dec 11, 2024

Thanks for sharing this solution! Really helped me understand the crypto.subtle.digest workflow.

I ended up iterating on your approach with some ES6+ optimizations - thought I'd share back in case it's useful for others:

/**
 * Generates a cryptographic hash of the input string using the specified algorithm.
 *
 * @async
 * @param {'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512'} algorithm - The algorithm to use for hashing
 * @param {string} input - The string to be hashed
 * @returns {Promise<string>} A promise that resolves to a hexadecimal string representing the hash
 */
const generateHash = async (algorithm, input) =>
  [
    ...new Uint8Array(
      await crypto.subtle.digest(
        algorithm,
        new TextEncoder().encode(input?.toString() ?? "")
      )
    ),
  ].reduce((hex, byte) => hex + byte.toString(16).padStart(2, "0"), "");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment