2022-12-03 05:23:13 +03:00
|
|
|
/**
|
|
|
|
* An **HMAC** enables verification that a given key was used
|
|
|
|
* to authenticate a payload.
|
|
|
|
*
|
|
|
|
* See: [[link-wiki-hmac]]
|
|
|
|
*
|
|
|
|
* @_subsection: api/crypto:HMAC [about-hmac]
|
|
|
|
*/
|
2022-10-25 11:06:00 +03:00
|
|
|
import { createHmac } from "./crypto.js";
|
2022-09-09 06:21:08 +03:00
|
|
|
import { getBytes, hexlify } from "../utils/index.js";
|
2022-09-05 23:14:43 +03:00
|
|
|
|
|
|
|
import type { BytesLike } from "../utils/index.js";
|
|
|
|
|
|
|
|
|
|
|
|
let locked = false;
|
|
|
|
|
|
|
|
const _computeHmac = function(algorithm: "sha256" | "sha512", key: Uint8Array, data: Uint8Array): BytesLike {
|
2022-10-20 11:58:37 +03:00
|
|
|
return createHmac(algorithm, key).update(data).digest();
|
2022-09-05 23:14:43 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
let __computeHmac = _computeHmac;
|
|
|
|
|
2022-12-03 05:23:13 +03:00
|
|
|
/**
|
|
|
|
* Return the HMAC for %%data%% using the %%key%% key with the underlying
|
|
|
|
* %%algo%% used for compression.
|
|
|
|
*/
|
2022-09-05 23:14:43 +03:00
|
|
|
export function computeHmac(algorithm: "sha256" | "sha512", _key: BytesLike, _data: BytesLike): string {
|
2022-09-09 06:21:08 +03:00
|
|
|
const key = getBytes(_key, "key");
|
|
|
|
const data = getBytes(_data, "data");
|
2022-09-05 23:14:43 +03:00
|
|
|
return hexlify(__computeHmac(algorithm, key, data));
|
|
|
|
}
|
|
|
|
computeHmac._ = _computeHmac;
|
|
|
|
computeHmac.lock = function() { locked = true; }
|
|
|
|
computeHmac.register = function(func: (algorithm: "sha256" | "sha512", key: Uint8Array, data: Uint8Array) => BytesLike) {
|
|
|
|
if (locked) { throw new Error("computeHmac is locked"); }
|
|
|
|
__computeHmac = func;
|
|
|
|
}
|
|
|
|
Object.freeze(computeHmac);
|