UNPKG

1.22 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util-crypto authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3import { hmac } from '@noble/hashes/hmac';
4import { sha256 } from '@noble/hashes/sha256';
5import { sha512 } from '@noble/hashes/sha512';
6import { hasBigInt, u8aToU8a } from '@polkadot/util';
7import { hmacSha256, hmacSha512, isReady } from '@polkadot/wasm-crypto';
8const JS_HASH = {
9 256: sha256,
10 512: sha512
11};
12const WA_MHAC = {
13 256: hmacSha256,
14 512: hmacSha512
15};
16
17function createSha(bitLength) {
18 return (key, data, onlyJs) => hmacShaAsU8a(key, data, bitLength, onlyJs);
19}
20/**
21 * @name hmacShaAsU8a
22 * @description creates a Hmac Sha (256/512) Uint8Array from the key & data
23 */
24
25
26export function hmacShaAsU8a(key, data, bitLength = 256, onlyJs) {
27 const u8aKey = u8aToU8a(key);
28 return !hasBigInt || !onlyJs && isReady() ? WA_MHAC[bitLength](u8aKey, data) : hmac(JS_HASH[bitLength], u8aKey, data);
29}
30/**
31 * @name hmacSha256AsU8a
32 * @description creates a Hmac Sha256 Uint8Array from the key & data
33 */
34
35export const hmacSha256AsU8a = createSha(256);
36/**
37 * @name hmacSha512AsU8a
38 * @description creates a Hmac Sha512 Uint8Array from the key & data
39 */
40
41export const hmacSha512AsU8a = createSha(512);
\No newline at end of file