高熵值随机字符生成工具
/**
* 生成高熵加密随机字符串(仅字母数字)
* @param length 生成的字符串长度 (正整数)
* @returns 由大小写字母和数字组成的随机字符串
* @throws 参数错误或环境不支持时抛出异常
*/
export function generateHighEntropyString(length: number): string {
// 严格参数校验
if (!Number.isSafeInteger(length) || length <= 0) {
throw new Error('Invalid length: must be a positive integer');
}
// 定义纯字母数字字符池(共62字符)
const CHARSET = {
UPPERCASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
LOWERCASE: 'abcdefghijklmnopqrstuvwxyz',
NUMBERS: '0123456789'
};
// 合并字符集(26 + 26 + 10 = 62字符)
const charPool = [
CHARSET.UPPERCASE,
CHARSET.LOWERCASE,
CHARSET.NUMBERS
].join('');
// 创建随机字节缓冲区
const buffer = new Uint8Array(length);
// 仅使用浏览器加密API
if (typeof crypto === 'undefined' || !crypto.getRandomValues) {
throw new Error('Web Crypto API is not available in this environment');
}
crypto.getRandomValues(buffer);
// 构建结果字符串
let result = '';
for (let i = 0; i < length; i++) {
// 优化模运算分布:先转换成32位整型再取模
const randomValue = buffer[i] >>> 0; // 转换为无符号整型
result += charPool[randomValue % charPool.length];
}
return result;
}
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。