/// SPDX-License-Identifier: GPL-3.0-or-later /// SPDX-FileCopyrightText: Copyright © 2016-2024 Tony Garnock-Jones import { Bytes, underlying } from '@preserves/core'; import * as node_crypto from 'crypto'; import { makeHMAC, BLAKE2s } from 'salty-crypto'; export const KEY_LENGTH = 16; // 128 bits export const newKey: () => Promise = (typeof crypto !== 'undefined' && 'getRandomValues' in crypto) ? (async () => { const bs = new Bytes(KEY_LENGTH); crypto.getRandomValues(underlying(bs)); return bs; }) : (async () => Bytes.from(node_crypto.randomBytes(KEY_LENGTH))); const HMAC_BLAKE2s = makeHMAC(BLAKE2s); export function mac(secretKey: Bytes, data: Bytes): Bytes { return Bytes.from(HMAC_BLAKE2s(underlying(secretKey), underlying(data)) .subarray(0, KEY_LENGTH)); }