25 lines
636 B
JavaScript
25 lines
636 B
JavaScript
import { createHash, randomBytes } from 'node:crypto';
|
|
|
|
const CHARSET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
|
|
|
export function toBase62(buffer) {
|
|
let num = BigInt('0x' + buffer.toString('hex'));
|
|
if (num === 0n) return CHARSET[0].repeat(8);
|
|
let res = '';
|
|
while (num > 0n) {
|
|
res = CHARSET[Number(num % 62n)] + res;
|
|
num /= 62n;
|
|
}
|
|
return res;
|
|
}
|
|
|
|
export default function newFullHash(buffer) {
|
|
if (buffer) {
|
|
const digest = createHash('sha256').update(buffer).digest();
|
|
return toBase62(digest).slice(0, 8);
|
|
}
|
|
const bytes = randomBytes(16);
|
|
return toBase62(bytes).slice(0, 8);
|
|
}
|
|
|