From 280cba80d6fa81898f3403a4d8007b43207af11c Mon Sep 17 00:00:00 2001 From: Luk Date: Sat, 3 May 2025 15:12:05 +0800 Subject: [PATCH] rename 'hash_easy' to 'hash_stable' and use 'stringify_by_keyorder' to make sure a stable outcome --- tool_core.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tool_core.js b/tool_core.js index 632fb67..e1b41fb 100644 --- a/tool_core.js +++ b/tool_core.js @@ -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'