Skip to content

Instantly share code, notes, and snippets.

@nichoth
Last active November 7, 2023 04:20
Show Gist options
  • Save nichoth/b63e0853b32af3ba24ccd24adc99461e to your computer and use it in GitHub Desktop.
Save nichoth/b63e0853b32af3ba24ccd24adc99461e to your computer and use it in GitHub Desktop.
Create a sha256 hash in the browser
const webcrypto = window.crypto
import * as uint8arrays from 'uint8arrays'
// data should be Uint8Array
function getHash (data) {
let _data = data
if (typeof data === 'string') {
const te = new TextEncoder()
_data = te.encode(data)
}
return webcrypto.subtle.digest('SHA-256', _data).then(buf => {
return uint8arrays.toString(new Uint8Array(buf), 'base64url')
// this is hex version
// return Array.from(new Uint8Array(buf), b => {
// return b.toString(16).padStart(2, '0')
// }).join('')
}
}
@nichoth
Copy link
Author

nichoth commented Aug 3, 2022

@nichoth
Copy link
Author

nichoth commented Nov 7, 2023

export async function sha256(bytes: Uint8Array): Promise<Uint8Array> {
  return new Uint8Array(await webcrypto.subtle.digest("sha-256", bytes))
}

see https://github.com/oddsdk/ts-odd/blob/f90bde37416d9986d1c0afed406182a95ce7c1d7/src/components/crypto/implementation/browser.ts#L130

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