forked from TelemetryDeck/JavaScriptSDK
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsha256.js
More file actions
29 lines (25 loc) · 885 Bytes
/
sha256.js
File metadata and controls
29 lines (25 loc) · 885 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Calculate the SHA-256 hash of a string using a provided instance of SubtleCrypto
* (e.g. window.crypto.subtle).
*
* Requires `.digest()` to be available on the SubtleCrypto instance.
*
* Defaults to globalThis.crypto.subtle if available.
*
* // https://stackoverflow.com/a/48161723/54547
*
* @param {Function} subtleCrypto
* @param {string} message
* @returns {Promise<string>}
*/
export async function sha256(message, subtleCrypto = globalThis?.crypto?.subtle) {
// encode as UTF-8
const messageBuffer = new TextEncoder().encode(message);
// hash the message
const hashBuffer = await subtleCrypto.digest('SHA-256', messageBuffer);
// convert ArrayBuffer to Array
const hashArray = [...new Uint8Array(hashBuffer)];
// convert bytes to hex string
const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}