UNPKG

@zlattice/lattice-js

Version:

Lattice blockchain TypeScript SDK with dual module support (CJS + ESM)

71 lines 2.82 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.utf8ToArray = utf8ToArray; exports.sm3 = sm3; const hmac_1 = require("../../crypto/sm2/hmac.js"); const sm3_1 = require("../../crypto/sm2/sm3.js"); const utils_1 = require("../../crypto/sm2/utils.js"); const utils_2 = require("../../crypto/sm3/utils.js"); /** * 补全16进制字符串 */ // function leftPad(input, num) { // if (input.length >= num) return input // return (new Array(num - input.length + 1)).join('0') + input // } /** * utf8 串转字节数组 */ function utf8ToArray(str) { const arr = []; for (let i = 0, len = str.length; i < len; i++) { const point = str.codePointAt(i); if (!point) throw new Error('invalid input'); if (point <= 0x007f) { // 单字节,标量值:00000000 00000000 0zzzzzzz arr.push(point); } else if (point <= 0x07ff) { // 双字节,标量值:00000000 00000yyy yyzzzzzz arr.push(0xc0 | (point >>> 6)); // 110yyyyy(0xc0-0xdf) arr.push(0x80 | (point & 0x3f)); // 10zzzzzz(0x80-0xbf) } else if (point <= 0xD7FF || (point >= 0xE000 && point <= 0xFFFF)) { // 三字节:标量值:00000000 xxxxyyyy yyzzzzzz arr.push(0xe0 | (point >>> 12)); // 1110xxxx(0xe0-0xef) arr.push(0x80 | ((point >>> 6) & 0x3f)); // 10yyyyyy(0x80-0xbf) arr.push(0x80 | (point & 0x3f)); // 10zzzzzz(0x80-0xbf) } else if (point >= 0x010000 && point <= 0x10FFFF) { // 四字节:标量值:000wwwxx xxxxyyyy yyzzzzzz i++; arr.push((0xf0 | (point >>> 18) & 0x1c)); // 11110www(0xf0-0xf7) arr.push((0x80 | ((point >>> 12) & 0x3f))); // 10xxxxxx(0x80-0xbf) arr.push((0x80 | ((point >>> 6) & 0x3f))); // 10yyyyyy(0x80-0xbf) arr.push((0x80 | (point & 0x3f))); // 10zzzzzz(0x80-0xbf) } else { // 五、六字节,暂时不支持 arr.push(point); throw new Error('input is not supported'); } } return new Uint8Array(arr); } function sm3(input, options) { input = typeof input === 'string' ? utf8ToArray(input) : input; if (options) { const mode = options.mode || 'hmac'; if (mode !== 'hmac') throw new Error('invalid mode'); let key = options.key; if (!key) throw new Error('invalid key'); key = typeof key === 'string' ? (0, utils_1.hexToArray)(key) : key; return (0, utils_2.bytesToHex)((0, hmac_1.hmac)(sm3_1.sm3, key, input)); } return (0, utils_2.bytesToHex)((0, sm3_1.sm3)(input)); } exports.default = sm3; //# sourceMappingURL=index.js.map