Helpers for 256/512 hashing (#1303)

* Helpers for 256/512 hashing

* Adjust u8aToU8a (u8a-only check earlier)

* Fix export

* Simplify

* revert
This commit is contained in:
Jaco
2021-12-09 10:10:51 +02:00
committed by GitHub
parent 000d097de2
commit 7955022ce5
13 changed files with 93 additions and 102 deletions
+12 -7
View File
@@ -9,6 +9,16 @@ import { sha512 } from '@polkadot/x-noble-hashes/sha512';
type BitLength = 256 | 512;
const JS_HASH = {
256: sha256,
512: sha512
};
const WA_MHAC = {
256: hmacSha256,
512: hmacSha512
};
function createSha (bitLength: BitLength): (key: Uint8Array | string, data: Uint8Array, onlyJs?: boolean) => Uint8Array {
return (key: Uint8Array | string, data: Uint8Array, onlyJs?: boolean): Uint8Array =>
hmacShaAsU8a(key, data, bitLength, onlyJs);
@@ -19,16 +29,11 @@ function createSha (bitLength: BitLength): (key: Uint8Array | string, data: Uint
* @description creates a Hmac Sha (256/512) Uint8Array from the key & data
*/
export function hmacShaAsU8a (key: Uint8Array | string, data: Uint8Array, bitLength: BitLength = 256, onlyJs?: boolean): Uint8Array {
const is256 = bitLength === 256;
const u8aKey = u8aToU8a(key);
return !hasBigInt || (!onlyJs && isReady())
? is256
? hmacSha256(u8aKey, data)
: hmacSha512(u8aKey, data)
: is256
? hmac(sha256, u8aKey, data)
: hmac(sha512, u8aKey, data);
? WA_MHAC[bitLength](u8aKey, data)
: hmac(JS_HASH[bitLength], u8aKey, data);
}
/**