SM4.js 1.0 KB

1234567891011121314151617181920212223242526272829303132
  1. const sm4 = require('sm-crypto');
  2. //const sm4 = require('miniprogram-sm-crypto').sm4;
  3. function stringToHex(str) {
  4. console.log('stringToHex');
  5. const buffer = new ArrayBuffer(str.length);
  6. const view = new Uint8Array(buffer);
  7. for (let i = 0; i < str.length; i++) {
  8. view[i] = str.charCodeAt(i);
  9. }
  10. return Array.from(view, byte => byte.toString(16).padStart(2, '0')).join('');
  11. }
  12. function sm4EcbEncrypt(plaintext, key) {
  13. // 确保密钥是32字符的十六进制字符串
  14. if (key.length !== 32 || !/^[0-9a-fA-F]+$/.test(key)) {
  15. throw new Error('密钥必须是32字符的十六进制字符串');
  16. }
  17. console.log('plaintext :' + plaintext);
  18. // 使用 sm-crypto 进行 SM4 ECB 加密
  19. const ciphertextHex = sm4.sm4.encrypt(plaintext,key);
  20. console.log('ciphertextHex :' + ciphertextHex);
  21. // 将明文转换为十六进制字符串
  22. const plaintextHex = stringToHex(ciphertextHex);
  23. console.log('plaintextHex :' + plaintextHex);
  24. return plaintextHex;
  25. }
  26. module.exports = {
  27. sm4EcbEncrypt,
  28. };