Skip to content

Commit f27cb7e

Browse files
committed
utils: use rand from webcrypto
1 parent a6eee48 commit f27cb7e

1 file changed

Lines changed: 13 additions & 3 deletions

File tree

framework/utils/lib/common.ts

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import { randomInt } from 'node:crypto';
2-
31
declare global {
42
interface String {
53
format: (...args: Array<any>) => string;
@@ -13,9 +11,21 @@ declare global {
1311

1412
const defaultDict = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
1513

14+
function randomInt(min: number, max: number) {
15+
const range = max - min + 1;
16+
const maxValid = Math.floor(4294967296 / range) * range;
17+
const array = new Uint32Array(1);
18+
let value: number;
19+
do {
20+
crypto.getRandomValues(array);
21+
value = array[0];
22+
} while (value >= maxValid);
23+
return min + (value % range);
24+
}
25+
1626
export function randomstring(digit = 32, dict = defaultDict) {
1727
let str = '';
18-
for (let i = 1; i <= digit; i++) str += dict[randomInt(dict.length)];
28+
for (let i = 1; i <= digit; i++) str += dict[randomInt(0, dict.length - 1)];
1929
return str;
2030
}
2131

0 commit comments

Comments
 (0)