2021-12-01 16:24:29 +00:00
|
|
|
/// SPDX-License-Identifier: GPL-3.0-or-later
|
2022-01-26 13:38:38 +00:00
|
|
|
/// SPDX-FileCopyrightText: Copyright © 2016-2022 Tony Garnock-Jones <tonyg@leastfixedpoint.com>
|
2018-11-01 14:55:45 +00:00
|
|
|
|
2021-05-17 14:26:01 +00:00
|
|
|
import { Bytes } from '@preserves/core';
|
2021-01-11 22:35:36 +00:00
|
|
|
import * as node_crypto from 'crypto';
|
2019-06-14 14:33:02 +00:00
|
|
|
|
2021-01-11 22:35:36 +00:00
|
|
|
export function _btoa(s: string): string {
|
|
|
|
try {
|
|
|
|
return btoa(s);
|
|
|
|
} catch (e) {
|
|
|
|
return Buffer.from(s).toString('base64');
|
|
|
|
}
|
2018-09-09 17:13:57 +00:00
|
|
|
}
|
|
|
|
|
2021-01-17 13:14:02 +00:00
|
|
|
function _finish(hexOutput: boolean, buf: Uint8Array): string {
|
2021-01-11 22:35:36 +00:00
|
|
|
if (hexOutput) {
|
|
|
|
return Bytes.from(buf).toHex();
|
|
|
|
} else {
|
2021-01-15 12:38:15 +00:00
|
|
|
return _btoa(String.fromCharCode.apply(null, buf as unknown as number[])).replace(/=/g,'');
|
2021-01-11 22:35:36 +00:00
|
|
|
}
|
|
|
|
}
|
2021-01-17 13:14:02 +00:00
|
|
|
|
|
|
|
export const randomId =
|
|
|
|
(typeof crypto !== 'undefined' && 'getRandomValues' in crypto)
|
|
|
|
? ((byteCount: number, hexOutput: boolean = false): string => {
|
|
|
|
const buf = new Uint8Array(byteCount);
|
|
|
|
crypto.getRandomValues(buf);
|
|
|
|
return _finish(hexOutput, buf);
|
|
|
|
})
|
|
|
|
: ((byteCount: number, hexOutput: boolean = false): string => {
|
|
|
|
let buf = node_crypto.randomBytes(byteCount);
|
|
|
|
return _finish(hexOutput, buf);
|
|
|
|
});
|