diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-19 00:47:55 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-19 00:47:55 +0000 |
commit | 26a029d407be480d791972afb5975cf62c9360a6 (patch) | |
tree | f435a8308119effd964b339f76abb83a57c29483 /toolkit/mozapps/extensions/internal/crypto-utils.sys.mjs | |
parent | Initial commit. (diff) | |
download | firefox-26a029d407be480d791972afb5975cf62c9360a6.tar.xz firefox-26a029d407be480d791972afb5975cf62c9360a6.zip |
Adding upstream version 124.0.1.upstream/124.0.1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'toolkit/mozapps/extensions/internal/crypto-utils.sys.mjs')
-rw-r--r-- | toolkit/mozapps/extensions/internal/crypto-utils.sys.mjs | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/toolkit/mozapps/extensions/internal/crypto-utils.sys.mjs b/toolkit/mozapps/extensions/internal/crypto-utils.sys.mjs new file mode 100644 index 0000000000..b1304bcdfc --- /dev/null +++ b/toolkit/mozapps/extensions/internal/crypto-utils.sys.mjs @@ -0,0 +1,57 @@ +/* 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" +); + +export function computeHashAsString(hashType, input) { + const data = new Uint8Array(new TextEncoder().encode(input)); + const crypto = CryptoHash(hashType); + crypto.update(data, data.length); + return getHashStringForCrypto(crypto); +} + +/** + * 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) { + return computeHashAsString("sha256", input); +} + +/** + * Returns the string representation (hex) of the SHA1 hash of `input`. + * + * @param {string} input + * The value to hash. + * @returns {string} + * The hex representation of a SHA1 hash. + */ +export function computeSha1HashAsString(input) { + return computeHashAsString("sha1", input); +} + +/** + * 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(); +} |