rename 'hash_easy' to 'hash_stable' and use 'stringify_by_keyorder' to make sure a stable outcome

This commit is contained in:
Luk 2025-05-03 15:12:05 +08:00
parent df386d8266
commit 280cba80d6

View File

@ -58,7 +58,6 @@ module.exports = {
stringify_by_keyorder (obj, { cmp, cycles = false, space = '', replacer, schemaColumns, excludeKeys = [] } = {}) {
/* 这个解决方法不考虑缺省值,不能把嵌套对象也按顺序展开。*/
// return JSON.stringify(obj, Object.keys(schemaColumns || entity).sort().filter(key => ! excludeKeys.includes(key))) // JSON.stringify 可根据第二个数组参数的顺序排序,但这导致了嵌套对象不能按顺序展开。
let newObj = {}
if (schemaColumns) {
for (let key in schemaColumns) {
@ -191,8 +190,8 @@ module.exports = {
return num
},
hash_easy (data, { hasher = 'sha256', salt, input = 'utf8', output = 'hex' } = {}) {
if (typeof data !== 'string' && !(data instanceof Buffer) && !(data instanceof DataView)) data = JSON.stringify(data)
hash_stable (data, { hasher = 'sha256', salt, input = 'utf8', output = 'hex' } = {}) {
if (typeof data !== 'string' && !(data instanceof Buffer) && !(data instanceof DataView)) data = this.stringify_by_keyorder(data)
if (salt && typeof salt === 'string') data = data + salt
const inputEncoding = input // my.INPUT_LIST.indexOf(option.input)>=0?option.input:my.INPUT // 'utf8', 'ascii' or 'latin1' for string data, default to utf8 if not specified; ignored for Buffer, TypedArray, or DataView.
const outputEncoding = output === 'buf' ? undefined : output // (my.OUTPUT_LIST.indexOf(output)>=0?output:my.OUTPUT) // option.output: 留空=》默认输出hex格式或者手动指定 'buf', hex', 'latin1' or 'base64'