const sm4 = require('sm-crypto'); //const sm4 = require('miniprogram-sm-crypto').sm4; function stringToHex(str) { console.log('stringToHex'); const buffer = new ArrayBuffer(str.length); const view = new Uint8Array(buffer); for (let i = 0; i < str.length; i++) { view[i] = str.charCodeAt(i); } return Array.from(view, byte => byte.toString(16).padStart(2, '0')).join(''); } function sm4EcbEncrypt(plaintext, key) { // 确保密钥是32字符的十六进制字符串 if (key.length !== 32 || !/^[0-9a-fA-F]+$/.test(key)) { throw new Error('密钥必须是32字符的十六进制字符串'); } console.log('plaintext :' + plaintext); // 使用 sm-crypto 进行 SM4 ECB 加密 const ciphertextHex = sm4.sm4.encrypt(plaintext,key); console.log('ciphertextHex :' + ciphertextHex); // 将明文转换为十六进制字符串 const plaintextHex = stringToHex(ciphertextHex); console.log('plaintextHex :' + plaintextHex); return plaintextHex; } module.exports = { sm4EcbEncrypt, };