feat: replace js-sha512 with @noble/hashes for SHA-512 implementation and update related logic

This commit is contained in:
2026-01-03 06:47:45 +00:00
parent 4f90f50033
commit 7b41852938
5 changed files with 62 additions and 12 deletions
+1
View File
@@ -9,3 +9,4 @@ export * from './util/JosaUtil.js';
export * from './util/RNG.js';
export * from './util/RandUtil.js';
export * from './util/TestRNG.js';
export * from './util/sha512.js';
+2 -3
View File
@@ -1,9 +1,8 @@
import type { RNG } from './RNG.js';
import { sha512 } from 'js-sha512';
import { convertBytesLikeToUint8Array } from './convertBytesLikeToUint8Array.js';
import type { BytesLike } from './BytesLike.js';
import { sha512ArrayBuffer } from './sha512.js';
const maxRngSupportBit = 53;
const maxInt = 0x1f_ffff_ffff_ffff; // NOTE: b 0, 10000110011, 11...11
@@ -111,7 +110,7 @@ export class LiteHashDRBG implements RNG {
protected genNextBlock(): void {
this.hq.setUint32(this.hqIdxPos, this.stateIdx, true);
const digest = sha512.arrayBuffer(this.hq.buffer as ArrayBuffer);
const digest = sha512ArrayBuffer(this.hq.buffer as ArrayBuffer);
this.buffer = digest;
this.bufferIdx = 0;
this.stateIdx += 1;
+49
View File
@@ -0,0 +1,49 @@
import { sha512 as sha512Noble } from '@noble/hashes/sha2.js';
import type { BytesLike } from './BytesLike.js';
import { convertBytesLikeToUint8Array } from './convertBytesLikeToUint8Array.js';
type NodeHash = {
update(data: Uint8Array): NodeHash;
digest(): Uint8Array;
};
type NodeCreateHash = (algorithm: 'sha512') => NodeHash;
const isNode = typeof process !== 'undefined'
&& typeof process.versions?.node === 'string';
const nodeCryptoSpecifier = 'node:crypto';
let nodeCreateHash: NodeCreateHash | null = null;
if (isNode) {
const nodeCrypto = await import(nodeCryptoSpecifier) as typeof import('node:crypto');
nodeCreateHash = nodeCrypto.createHash as NodeCreateHash;
}
function normalizeUint8Array(bytes: Uint8Array): Uint8Array<ArrayBuffer> {
if (
bytes.buffer instanceof ArrayBuffer
&& bytes.byteOffset === 0
&& bytes.byteLength === bytes.buffer.byteLength
) {
return bytes as Uint8Array<ArrayBuffer>;
}
const out = new Uint8Array(bytes.byteLength);
out.set(bytes);
return out as Uint8Array<ArrayBuffer>;
}
export function sha512Bytes(data: BytesLike): Uint8Array<ArrayBuffer> {
const input = convertBytesLikeToUint8Array(data);
if (nodeCreateHash) {
const digest = nodeCreateHash('sha512').update(input).digest();
return normalizeUint8Array(digest);
}
return normalizeUint8Array(sha512Noble(input));
}
export function sha512ArrayBuffer(data: BytesLike): ArrayBuffer {
return sha512Bytes(data).buffer;
}