UNPKG

1.17 kBJavaScriptView Raw
1import { hmac } from '@noble/hashes/hmac';
2import { sha256 } from '@noble/hashes/sha256';
3import { sha512 } from '@noble/hashes/sha512';
4import { hasBigInt, u8aToU8a } from '@polkadot/util';
5import { hmacSha256, hmacSha512, isReady } from '@polkadot/wasm-crypto';
6const JS_HASH = {
7 256: sha256,
8 512: sha512
9};
10const WA_MHAC = {
11 256: hmacSha256,
12 512: hmacSha512
13};
14function createSha(bitLength) {
15 return (key, data, onlyJs) => hmacShaAsU8a(key, data, bitLength, onlyJs);
16}
17/**
18 * @name hmacShaAsU8a
19 * @description creates a Hmac Sha (256/512) Uint8Array from the key & data
20 */
21export function hmacShaAsU8a(key, data, bitLength = 256, onlyJs) {
22 const u8aKey = u8aToU8a(key);
23 return !hasBigInt || (!onlyJs && isReady())
24 ? WA_MHAC[bitLength](u8aKey, data)
25 : hmac(JS_HASH[bitLength], u8aKey, data);
26}
27/**
28 * @name hmacSha256AsU8a
29 * @description creates a Hmac Sha256 Uint8Array from the key & data
30 */
31export const hmacSha256AsU8a = /*#__PURE__*/ createSha(256);
32/**
33 * @name hmacSha512AsU8a
34 * @description creates a Hmac Sha512 Uint8Array from the key & data
35 */
36export const hmacSha512AsU8a = /*#__PURE__*/ createSha(512);