24 lines
845 B
TypeScript
24 lines
845 B
TypeScript
/// SPDX-License-Identifier: GPL-3.0-or-later
|
|
/// SPDX-FileCopyrightText: Copyright © 2016-2023 Tony Garnock-Jones <tonyg@leastfixedpoint.com>
|
|
|
|
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<Bytes> =
|
|
(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 async function mac(secretKey: Bytes, data: Bytes): Promise<Bytes> {
|
|
return Bytes.from(HMAC_BLAKE2s(underlying(secretKey), underlying(data)));
|
|
}
|