您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

encryption.js 6.7KB

1 个月前
1 个月前
1 个月前
1 个月前
1 个月前
1 个月前
1 个月前
1 个月前
1 个月前
1 个月前
1 个月前
1 个月前
1 个月前
1 个月前
1 个月前
1 个月前
1 个月前
1 个月前
1 个月前
1 个月前
1 个月前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. const ksort = require("./ksort.js").ksort;
  2. const md5 = require("./md5.js").md5;
  3. const sha1 = require("./sha1.js").sha1;
  4. const {
  5. default: SM4Util
  6. } = require('./sm4');
  7. const sm3 = require('./SM3.js').sm3;
  8. const {configObj, isNeedEncry} = require("../config.js");
  9. const _signCode = "etc123456"; //签名码
  10. const s4 = new SM4Util();
  11. /**
  12. * 数字补零函数
  13. * @param {number} n - 需要补零的数字
  14. * @param {boolean} isMill - 是否为毫秒
  15. * @returns {string} 补零后的字符串
  16. */
  17. function pad2(n, isMill = false) {
  18. if (isMill) {
  19. if (n < 10) {
  20. return "00" + n
  21. } else if (n < 100 && n >= 10) {
  22. return "0" + n
  23. } else {
  24. return n
  25. }
  26. } else {
  27. return n < 10 ? "0" + n : n;
  28. }
  29. }
  30. function sm4Decrypt(bizContent) {
  31. const decrypted = s4.decryptData_CBC({
  32. data: {
  33. bizContent
  34. }
  35. }, configObj.sm4Key)
  36. if (decrypted.data && decrypted.data.bizContent) {
  37. return JSON.parse(decrypted.data.bizContent)
  38. }
  39. }
  40. /**
  41. * 获取时间ymdHis格式
  42. * @returns {string} 时间字符串
  43. */
  44. function getDate() {
  45. var date = new Date();
  46. return (
  47. date.getFullYear().toString() +
  48. pad2(date.getMonth() + 1) +
  49. pad2(date.getDate()) +
  50. pad2(date.getHours()) +
  51. pad2(date.getMinutes()) +
  52. pad2(date.getSeconds()) +
  53. pad2(date.getMilliseconds(), true)
  54. );
  55. }
  56. /**
  57. * 获取随机数
  58. * @param {number} n - 随机数长度
  59. * @returns {string} 随机数字符串
  60. */
  61. function generateMixed(n) {
  62. var chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
  63. var res = "";
  64. for (var i = 0; i < n; i++) {
  65. var id = Math.ceil(Math.random() * 8);
  66. res += chars[id];
  67. }
  68. return res;
  69. }
  70. /**
  71. * 签名函数
  72. * @param {Object} data - 需要签名的数据
  73. * @param {string} signCode - 签名码
  74. * @returns {string|boolean} 签名结果或false
  75. */
  76. function sign(data, signCode) {
  77. data = ksort(data);
  78. var signStr = "";
  79. var requestId = false;
  80. for (let k in data) {
  81. if (k != "sign") {
  82. if (k == "requestId") {
  83. requestId = data[k];
  84. }
  85. signStr += k + "=" + data[k] + "&";
  86. }
  87. }
  88. signStr += "signCode=" + signCode;
  89. // console.log("signStr*************"+signStr);
  90. if (!requestId) {
  91. return false;
  92. }
  93. signStr = md5(signStr);
  94. signStr = signStr.toUpperCase();
  95. // console.log('MD5**************' + signStr);
  96. signStr += requestId;
  97. // console.log('requestId**************' + signStr);
  98. signStr = sha1(signStr);
  99. signStr = signStr.toUpperCase();
  100. // console.log('SHA1**************' + signStr);
  101. return signStr;
  102. }
  103. /**
  104. * arrayToJsonString array 转json字符串
  105. * @param {Array} array - 需要转换的数组
  106. * @returns {string} JSON字符串
  107. */
  108. function arrayToJsonString(array) {
  109. var json = {};
  110. for (var i in array) {
  111. if (array[i] instanceof Array) {
  112. json[i] = {};
  113. for (var o in array[i]) {
  114. if (array[i][o] instanceof Array) {
  115. json[i][o] = {};
  116. for (var q in array[i][o]) {
  117. if (array[i][o][q] instanceof Array) {
  118. json[i][o][q] = {};
  119. for (var w in array[i][o][q]) {
  120. json[i][o][q][w] = array[i][o][q][w];
  121. }
  122. } else {
  123. json[i][o][q] = array[i][o][q];
  124. }
  125. }
  126. } else {
  127. json[i][o] = array[i][o];
  128. }
  129. }
  130. } else {
  131. json[i] = array[i];
  132. }
  133. }
  134. return JSON.stringify(json);
  135. }
  136. /**
  137. * json字符串转换成json对象
  138. * @param {string} data - JSON字符串
  139. * @returns {Object} JSON对象
  140. */
  141. function stringToJson(data) {
  142. return JSON.parse(data);
  143. }
  144. /**
  145. * array转json对象
  146. * @param {Array} array - 需要转换的数组
  147. * @returns {Object} JSON对象
  148. */
  149. function arrayToJson(array) {
  150. return stringToJson(arrayToJsonString(array));
  151. }
  152. /**
  153. * 时间格式化
  154. * @param {Date} date - 日期对象
  155. * @returns {string} 格式化后的时间字符串
  156. */
  157. function formatTime(date) {
  158. const year = date.getFullYear();
  159. const month = date.getMonth() + 1;
  160. const day = date.getDate();
  161. const hour = date.getHours();
  162. const minute = date.getMinutes();
  163. const second = date.getSeconds();
  164. return `${[year, month, day].map(formatNumber).join("-")}T${[
  165. hour,
  166. minute,
  167. second,
  168. ]
  169. .map(formatNumber)
  170. .join(":")}`;;
  171. }
  172. /**
  173. * 数字格式化
  174. * @param {number} n - 需要格式化的数字
  175. * @returns {string} 格式化后的字符串
  176. */
  177. function formatNumber(n) {
  178. n = n.toString();
  179. return n[1] ? n : `0${n}`;
  180. }
  181. /**
  182. * 获取Token函数(需要根据实际情况实现)
  183. * @returns {string|null} Token字符串或null
  184. */
  185. function getToken() {
  186. // 这里需要根据实际情况实现获取token的逻辑
  187. // 暂时返回null
  188. return null;
  189. }
  190. /**
  191. * 调用中台参数加密函数
  192. * @param {string} ifCode - 接口编码
  193. * @param {Object} subdata - 需要加密的数据
  194. * @param {string} type - 类型(可选)
  195. * @returns {Object} 加密后的数据对象
  196. */
  197. function encryption(ifCode, subdata, type) {
  198. try {
  199. console.log('开始加密处理,接口编码:', ifCode);
  200. console.log('原始数据:', subdata);
  201. let requestData = new Array();
  202. requestData["ifCode"] = ifCode;
  203. requestData["appId"] = configObj.reqEtcAppId; //"52088945";
  204. requestData["encryptType"] = configObj.reqEncryptType;
  205. // 执行SM4加密
  206. console.log("sm4Key", configObj.sm4Key)
  207. // 是否需要加密
  208. if (isNeedEncry()) {
  209. requestData["bizContent"] = s4.encryptData_CBC(subdata, configObj.sm4Key);
  210. } else {
  211. requestData["bizContent"] = JSON.stringify(subdata);
  212. }
  213. console.log('加密后的bizContent:', requestData["bizContent"]);
  214. requestData["reqId"] = requestData["appId"] + "_" + getDate() + "_" + generateMixed(5);
  215. requestData["timestamp"] = formatTime(new Date());
  216. // 生产环境
  217. let token = getToken();
  218. requestData['signType'] = 'SM3';
  219. let sm3Data = 'appId=' + requestData['appId'] +
  220. '&bizContent=' + requestData['bizContent'] +
  221. '&signType=' + requestData['signType'] +
  222. '&encryptType=' + requestData["encryptType"] +
  223. '&timestamp=' + requestData['timestamp'] +
  224. '&ifCode=' + ifCode +
  225. '&reqId=' + requestData['reqId'];
  226. if (token) {
  227. requestData['accessToken'] = token;
  228. sm3Data += `&accessToken=${token}`;
  229. }
  230. console.log("sm3Data原始数据:" + sm3Data)
  231. console.log("sm3Key:", configObj.sm3Key)
  232. requestData['sign'] = sm3(sm3Data, configObj.sm3Key);
  233. console.log("sign:" + requestData['sign'])
  234. let endData = arrayToJson(requestData);
  235. console.log('最终加密数据:', endData);
  236. return endData;
  237. } catch (error) {
  238. console.error('加密过程出错:', error);
  239. throw error;
  240. }
  241. }
  242. // CommonJS 导出
  243. module.exports = {
  244. arrayToJsonString,
  245. stringToJson,
  246. arrayToJson,
  247. formatTime,
  248. encryption,
  249. sm4Decrypt,
  250. };