const SM3 = require("../miniprogram_npm/sm-crypto/index.js"); /** * SM3 哈希函数,支持HMAC模式 * @param {string} message - 需要哈希的消息 * @param {string} key - 可选的密钥,用于HMAC模式 * @returns {string} 返回大写的哈希值 */ function sm3(message, key) { try { console.log('SM3 哈希开始,消息:', message); console.log('SM3 密钥:', key); // 在小程序环境中直接使用字符串,不使用Buffer if (key) { // HMAC-SM3 模式 const hmac = SM3.sm3(stringToArrayBuffer(message), { key: stringToArrayBuffer(key) }); console.log('HMAC-SM3 结果:', hmac); return hmac?.toUpperCase(); } else { // 普通SM3哈希 const hash = SM3.sm3(message); console.log('SM3 哈希结果:', hash); return hash?.toUpperCase(); } } catch (error) { console.error('SM3 哈希失败:', error); throw error; } } function stringToArrayBuffer(str) { // 优先使用 TextEncoder if (typeof TextEncoder !== 'undefined') { try { const encoder = new TextEncoder() return encoder.encode(str) } catch (error) { console.warn('TextEncoder failed, using fallback', error) return fallbackEncodeToUint8Array(str) } } else { return fallbackEncodeToUint8Array(str) } } function fallbackEncodeToUint8Array(str) { const len = str.length let bytes = [] let offset = 0 for (let i = 0; i < len; i++) { let charCode = str.charCodeAt(i) // UTF-8 编码 if (charCode <= 0x7F) { // 1字节: 0xxxxxxx bytes[offset++] = charCode } else if (charCode <= 0x7FF) { // 2字节: 110xxxxx 10xxxxxx bytes[offset++] = 0xC0 | (charCode >> 6) bytes[offset++] = 0x80 | (charCode & 0x3F) } else if (charCode <= 0xFFFF) { // 3字节: 1110xxxx 10xxxxxx 10xxxxxx bytes[offset++] = 0xE0 | (charCode >> 12) bytes[offset++] = 0x80 | ((charCode >> 6) & 0x3F) bytes[offset++] = 0x80 | (charCode & 0x3F) } else { // 4字节: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx (代理对) bytes[offset++] = 0xF0 | (charCode >> 18) bytes[offset++] = 0x80 | ((charCode >> 12) & 0x3F) bytes[offset++] = 0x80 | ((charCode >> 6) & 0x3F) bytes[offset++] = 0x80 | (charCode & 0x3F) } } return new Uint8Array(bytes) } module.exports = { sm3: sm3 }