syndicate-js/packages/core/src/transport/cryptography.ts

25 lines
863 B
TypeScript
Raw Normal View History

2021-12-01 16:24:29 +00:00
/// SPDX-License-Identifier: GPL-3.0-or-later
2024-02-03 14:59:22 +00:00
/// SPDX-FileCopyrightText: Copyright © 2016-2024 Tony Garnock-Jones <tonyg@leastfixedpoint.com>
2021-12-01 15:27:06 +00:00
import { Bytes, underlying } from '@preserves/core';
import * as node_crypto from 'crypto';
2023-02-06 16:34:15 +00:00
import { makeHMAC, BLAKE2s } from 'salty-crypto';
2021-12-01 15:27:06 +00:00
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)));
2023-02-06 16:34:15 +00:00
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));
2023-02-06 16:34:15 +00:00
}