blob: d242948dfd0eeb4d93d9c26f4f4593cca99c6cee (
plain)
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
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const CryptoHash = Components.Constructor(
"@mozilla.org/security/hash;1",
"nsICryptoHash",
"initWithString"
);
/**
* Returns the string representation (hex) of the SHA256 hash of `input`.
*
* @param {string} input
* The value to hash.
* @returns {string}
* The hex representation of a SHA256 hash.
*/
export function computeSha256HashAsString(input) {
const data = new Uint8Array(new TextEncoder().encode(input));
const crypto = CryptoHash("sha256");
crypto.update(data, data.length);
return getHashStringForCrypto(crypto);
}
/**
* Returns the string representation (hex) of a given CryptoHashInstance.
*
* @param {CryptoHash} aCrypto
* @returns {string}
* The hex representation of a SHA256 hash.
*/
export function getHashStringForCrypto(aCrypto) {
// return the two-digit hexadecimal code for a byte
let toHexString = charCode => ("0" + charCode.toString(16)).slice(-2);
// convert the binary hash data to a hex string.
let binary = aCrypto.finish(/* base64 */ false);
let hash = Array.from(binary, c => toHexString(c.charCodeAt(0)));
return hash.join("").toLowerCase();
}
|