-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbrowser-hash.js
79 lines (70 loc) · 2.35 KB
/
browser-hash.js
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* Determine if a value is a valid ArrayBuffer or TypedArray.
*
* @param {*} val - the value to check
* @returns {boolean}
*/
export function isBuffer(val) {
const buffer = val && val.buffer ? val.buffer : val;
return (
Boolean(buffer)
&& buffer.constructor === ArrayBuffer
&& !(val instanceof DataView)
);
}
/**
* Convert a string into a UTF-8 encoded Uint8Array.
*
* @param {string} str - the string to convert
* @returns {Uint8Array}
*/
export function stringToBuffer(str) {
if (typeof str !== "string") {
throw new TypeError(`Attempted to convert string, got: ${typeof str}`);
}
return new TextEncoder().encode(str);
}
/**
* Convert an ArrayBuffer or TypedArray into a hexadecimal string.
*
* @param {ArrayBuffer | TypedArray} buffer - the buffer to convert
* @returns {string} - a hex string
*/
export function bufferToHex(buffer) {
if (!isBuffer(buffer)) {
throw new TypeError(`Attempted to convert buffer, got: ${typeof buffer}`);
}
return Array.from(new Uint8Array(buffer))
.map(byte => byte.toString(16).padStart(2, "0"))
.join("");
}
function convertAndHash(strOrBuffer, algo) {
let buffer = isBuffer(strOrBuffer)
? strOrBuffer
: stringToBuffer(strOrBuffer);
return window.crypto.subtle.digest(algo, buffer);
}
/**
* Asynchronously hash a string or array buffer using native functionality,
* returning the digest formatted as a Uint8Array.
*
* @param {string | ArrayBuffer | TypedArray} strOrBuffer - the value to hash
* @param {string} [algo] - a valid algorithm name string
* @returns {Promise<Uint8Array>} - the digest formatted as a Uint8Array
*/
export async function bufferHash(strOrBuffer, algo = "SHA-256") {
let digest = await convertAndHash(strOrBuffer, algo);
return new Uint8Array(digest);
}
/**
* Asynchronously hash a string or array buffer using native functionality,
* returning the digest formatted as a hexadecimal string.
*
* @param {string | ArrayBuffer | TypedArray} strOrBuffer - the value to hash
* @param {string} [algo] - a valid algorithm name string
* @returns {Promise<string>} - the digest formatted as a hexadecimal string
*/
export default async function browserHash(strOrBuffer, algo = "SHA-256") {
let digest = await convertAndHash(strOrBuffer, algo);
return bufferToHex(digest);
}