Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

SM3.js 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. const SM3 = require("../miniprogram_npm/sm-crypto/index.js");
  2. /**
  3. * SM3 哈希函数,支持HMAC模式
  4. * @param {string} message - 需要哈希的消息
  5. * @param {string} key - 可选的密钥,用于HMAC模式
  6. * @returns {string} 返回大写的哈希值
  7. */
  8. function sm3(message, key) {
  9. try {
  10. console.log('SM3 哈希开始,消息:', message);
  11. console.log('SM3 密钥:', key);
  12. // 在小程序环境中直接使用字符串,不使用Buffer
  13. if (key) {
  14. // HMAC-SM3 模式
  15. const hmac = SM3.sm3(stringToArrayBuffer(message), {
  16. key: stringToArrayBuffer(key)
  17. });
  18. console.log('HMAC-SM3 结果:', hmac);
  19. return hmac?.toUpperCase();
  20. } else {
  21. // 普通SM3哈希
  22. const hash = SM3.sm3(message);
  23. console.log('SM3 哈希结果:', hash);
  24. return hash?.toUpperCase();
  25. }
  26. } catch (error) {
  27. console.error('SM3 哈希失败:', error);
  28. throw error;
  29. }
  30. }
  31. function stringToArrayBuffer(str) {
  32. // 优先使用 TextEncoder
  33. if (typeof TextEncoder !== 'undefined') {
  34. try {
  35. const encoder = new TextEncoder()
  36. return encoder.encode(str)
  37. } catch (error) {
  38. console.warn('TextEncoder failed, using fallback', error)
  39. return fallbackEncodeToUint8Array(str)
  40. }
  41. } else {
  42. return fallbackEncodeToUint8Array(str)
  43. }
  44. }
  45. function fallbackEncodeToUint8Array(str) {
  46. const len = str.length
  47. let bytes = []
  48. let offset = 0
  49. for (let i = 0; i < len; i++) {
  50. let charCode = str.charCodeAt(i)
  51. // UTF-8 编码
  52. if (charCode <= 0x7F) {
  53. // 1字节: 0xxxxxxx
  54. bytes[offset++] = charCode
  55. } else if (charCode <= 0x7FF) {
  56. // 2字节: 110xxxxx 10xxxxxx
  57. bytes[offset++] = 0xC0 | (charCode >> 6)
  58. bytes[offset++] = 0x80 | (charCode & 0x3F)
  59. } else if (charCode <= 0xFFFF) {
  60. // 3字节: 1110xxxx 10xxxxxx 10xxxxxx
  61. bytes[offset++] = 0xE0 | (charCode >> 12)
  62. bytes[offset++] = 0x80 | ((charCode >> 6) & 0x3F)
  63. bytes[offset++] = 0x80 | (charCode & 0x3F)
  64. } else {
  65. // 4字节: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx (代理对)
  66. bytes[offset++] = 0xF0 | (charCode >> 18)
  67. bytes[offset++] = 0x80 | ((charCode >> 12) & 0x3F)
  68. bytes[offset++] = 0x80 | ((charCode >> 6) & 0x3F)
  69. bytes[offset++] = 0x80 | (charCode & 0x3F)
  70. }
  71. }
  72. return new Uint8Array(bytes)
  73. }
  74. module.exports = {
  75. sm3: sm3
  76. }