import { Buffer } from "buffer"; const baseEncodeTables = { 26: "abcdefghijklmnopqrstuvwxyz", 32: "123456789abcdefghjkmnpqrstuvwxyz", // no 0lio 36: "0123456789abcdefghijklmnopqrstuvwxyz", 49: "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no lIO 52: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 58: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no 0lIO 62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 64: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_", }; /** * @param {Uint32Array} uint32Array Treated as a long base-0x100000000 number, little endian * @param {number} divisor The divisor * @return {number} Modulo (remainder) of the division */ function divmod32(uint32Array: Uint32Array, divisor: number): number { let carry = 0; for (let i = uint32Array.length - 1; i >= 0; i--) { const value = carry * 0x100000000 + uint32Array[i]; carry = value % divisor; uint32Array[i] = Math.floor(value / divisor); } return carry; } function encodeBufferToBase( buffer: Buffer, base: keyof typeof baseEncodeTables, length: number ) { const encodeTable: string = baseEncodeTables[base]; if (!encodeTable) { throw new Error("Unknown encoding base" + base); } // Input bits are only enough to generate this many characters const limit = Math.ceil((buffer.length * 8) / Math.log2(base)); length = Math.min(length, limit); // Most of the crypto digests (if not all) has length a multiple of 4 bytes. // Fewer numbers in the array means faster math. const uint32Array = new Uint32Array(Math.ceil(buffer.length / 4)); // Make sure the input buffer data is copied and is not mutated by reference. // divmod32() would corrupt the BulkUpdateDecorator cache otherwise. buffer.copy(Buffer.from(uint32Array.buffer)); let output = ""; for (let i = 0; i < length; i++) { output = encodeTable[divmod32(uint32Array, base)] + output; } return output; } // 不进行加密,加密太麻烦了 function getHashDigest( buffer: Buffer, algorithm: string, digestType: string, maxLength: number ) { maxLength = maxLength || 9999; const slice = buffer.slice(0, 127); return btoa(slice.join("")).substring(0, maxLength); } export default getHashDigest;