@joingo/sdk-security
Version:
SDK for JavaScript: Security Application Block!
91 lines (82 loc) • 4.04 kB
text/typescript
/* ************************************************************************************************************************ *\
* SDK for JavaScript! *
* *
* COPYRIGHT © 2021 BEIJING JOINGO INFORMATION TECHNOLOGY CO., LTD. ALL RIGHTS RESERVED. *
* LICENSED UNDER THE MIT LICENSE. SEE LICENSE FILE IN THE PROJECT ROOT FOR FULL LICENSE INFORMATION. *
* *
* AUTHOR : WANG YUCAI *
* E-MAIL ADDRESS: WANGYUCAI@JOINGO.VIP *
* DATE TIME : 2021-12-30 10:01 *
\* ************************************************************************************************************************ */
// CODEFILE: hash-number.ts
// FEATURE: 提供了数值哈希运算相关的方法。
// FILE-VERSION: v2021.12.30-build.1001
import { createException, isNullOrWhitespace } from "@joingo/sdk-core";
import Hashids from "hashids";
import { Nullable } from "@joingo/sdk-core";
/**
* 定义了计算哈希数值的配置类型。
*/
export type ComputeHashNumberOptionsConstructor = {
/**
* 设置或获取一个字符串,用于表示用于混淆的字母表。默认为 abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ。
*
* @type {string}
* @default 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
*/
salt?: string;
/**
* 设置或获取一个值,用于表示哈希数值最小程度。默认为 1。
*
* @type {number}
* @default 1
*/
minimalLength?: number;
};
/**
* 计算哈希数值的配置。
*/
const COMPUTE_HASHNUMBER_OPTIONS: ComputeHashNumberOptionsConstructor = {
salt: "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",
minimalLength: 1
};
let internalHashidsInstance: Hashids = new Hashids(COMPUTE_HASHNUMBER_OPTIONS.salt, COMPUTE_HASHNUMBER_OPTIONS.minimalLength);
/**
* 配置计算哈希数值配置。
*
* @export
* @param {ComputeHashNumberOptionsConstructor} [options] 配置信息。
*/
export function configureComputeHashNumberOptions(options?: ComputeHashNumberOptionsConstructor): void {
const _options = Object.assign({}, COMPUTE_HASHNUMBER_OPTIONS, options);
COMPUTE_HASHNUMBER_OPTIONS.salt = _options.salt;
COMPUTE_HASHNUMBER_OPTIONS.minimalLength = _options.minimalLength;
internalHashidsInstance = new Hashids(_options.salt, _options.minimalLength);
}
/**
* 获取数值的哈希值。
*
* @export
* @param {number} num 数值,必须大于等于 0。
* @returns {string}
*/
export function computeHashNumber(num: number): string {
if (num < 0)
throw createException(`错误的数值 ${num}。必须是一个大于等于 0 的数值。`);
const hashStr: string = internalHashidsInstance.encode(num);
console.debug(`[DEBUG]: 数值 ${num} 等效的哈希值为 "${hashStr}"。`);
return hashStr;
}
/**
* 从哈希字符串转换为等效的数值。
*
* @export
* @param {string} hashStr 哈希字符串。
* @returns {Nullable<number | bigint>}
*/
export function getNumber(hashStr: string): Nullable<number | bigint> {
if (isNullOrWhitespace(hashStr)) return new Nullable<number | bigint>();
const numbers = internalHashidsInstance.decode(hashStr);
console.debug(`[DEBUG]: 哈希字符串 "${hashStr}" 转换完成。详情参见:%o`, { hashStr, numbers });
return new Nullable<number | bigint>(numbers.length > 0 ? numbers[0] : null);
}