商城系統(tǒng) 注冊

微信小程序接口加密如何實現(xiàn)

2020-09-27|HiShop
導(dǎo)讀:微信小程序請求的所有接口參數(shù)必須加密,那么小程序接口加密如何實現(xiàn)。...

微信小程序請求的所有接口參數(shù)必須加密,那么小程序接口加密如何實現(xiàn)。

微信小程序接口加密如何實現(xiàn)

微信小程序接口實現(xiàn)加密教程:

場景

小程序請求的所有接口參數(shù)必須加密,后臺返回數(shù)據(jù)也需要加密,并且增加Token驗證

一、小程序端功能編寫

1.下載一份Js版的aesUtil.js源碼。【注:文章末尾會貼出所有的相關(guān)類文件】 
2.下載一份Js版的md5.js源碼。 
3.在pulic.js中進(jìn)行加解密操作代碼如下,其中秘鑰和秘鑰偏移量要與后臺的一致。

微信小程序接口加密如何實現(xiàn)

  1. var CryptoJS = require('aesUtil.js'); //引用AES源碼js
  2. var md5 = require('md5.js')
  3.  
  4. var key = CryptoJS.enc.Utf8.parse("76CAA1C88F7F8D1D"); //十六位十六進(jìn)制數(shù)作為秘鑰
  5. var iv = CryptoJS.enc.Utf8.parse('91129048100F0494'); //十六位十六進(jìn)制數(shù)作為秘鑰偏移量
  6. //解密方法
  7. function Decrypt(word) {
  8. var encryptedHexStr = CryptoJS.enc.Hex.parse(word);
  9. var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  10. var decrypt = CryptoJS.AES.decrypt(srcs, key, {
  11. iv: iv,
  12. mode: CryptoJS.mode.CBC,
  13. padding: CryptoJS.pad.Pkcs7
  14. });
  15. var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  16. return decryptedStr.toString();
  17. }
  18. //加密方法
  19. function Encrypt(word) {
  20. var srcs = CryptoJS.enc.Utf8.parse(word);
  21. var encrypted = CryptoJS.AES.encrypt(srcs, key, {
  22. iv: iv,
  23. mode: CryptoJS.mode.CBC,
  24. padding: CryptoJS.pad.Pkcs7
  25. });
  26. return encrypted.ciphertext.toString().toUpperCase();
  27. }
  28.  
  29. //暴露接口
  30. module.exports.Decrypt = Decrypt;
  31. module.exports.Encrypt = Encrypt;

4.在網(wǎng)絡(luò)請求幫助類中進(jìn)行參數(shù)的加密和返回數(shù)據(jù)的解密操作。

 

  1. var aes = require('../utils/public.js')
  2. var md5 = require("../utils/md5.js")
  3.  
  4. ...
  5.  
  6. /**
  7. * 網(wǎng)絡(luò)請求
  8. */
  9. function request(method, loading, url, params, success, fail) {
  10. var url = BASE_URL + url;
  11. //請求參數(shù)轉(zhuǎn)為JSON字符串
  12. var jsonStr = JSON.stringify(params);
  13. console.log(url + ' params=> ' + jsonStr)
  14. //根據(jù)特定規(guī)則生成Token
  15. var token = productionToken(params);
  16. //加密請求參數(shù)
  17. var aesData = aes.Encrypt(jsonStr)
  18. console.log('請求=>明文參數(shù):' + jsonStr)
  19. console.log('請求=>加密參數(shù):' + aesData)
  20. ...
  21. wx.request({
  22. url: url,
  23. method: method,
  24. header: {
  25. 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
  26. 'Token': token
  27. },
  28. data: {
  29. aesData: aesData
  30. },
  31. // data: params,
  32. success: function(res) {
  33. //判斷請求結(jié)果是否成功
  34. if (res.statusCode == 200 && res.data != '' && res.data != null) {
  35. //解密返回數(shù)據(jù)
  36. console.log('返回=>加密數(shù)據(jù):' + res.data);
  37. var result = aes.Decrypt(res.data);
  38. console.log('返回=>明文數(shù)據(jù):'+result);
  39. success(JSON.parse(result))
  40. } else {
  41. fail()
  42. }
  43. },
  44. fail: function(res) {
  45. fail()
  46. },
  47. })
  48. }

其中生成Token的規(guī)則,【生成Token的規(guī)則可根據(jù)具體的業(yè)務(wù)邏輯自己定義,我這里使用的規(guī)則是根據(jù)請求參數(shù)的字母排序取其value并加上當(dāng)前時間戳再進(jìn)行MD5加密】

 

  1. /**
  2. * 生成Token
  3. */
  4. function productionToken(params) {
  5. var obj = util.objKeySort(params);
  6. var value = '';
  7. for (var item in obj) {
  8. value += obj[item];
  9. }
  10. //加上當(dāng)前時間戳
  11. value += util.getTokenDate(new Date())
  12. //去除所有空格
  13. value = value.replace(/\s+/g, "")
  14. //進(jìn)行UTF-8編碼
  15. value = encodeURI(value);
  16. //進(jìn)行MD5碼加密
  17. value = md5.hex_md5(value)
  18. return value;
  19. }
  20. //util的排序函數(shù)
  21. function objKeySort(obj) {
  22. //先用Object內(nèi)置類的keys方法獲取要排序?qū)ο蟮膶傩悦?,再利用Array原型上的sort方法對獲取的屬性名進(jìn)行排序,newkey是一個數(shù)組
  23. var newkey = Object.keys(obj).sort();
  24. //創(chuàng)建一個新的對象,用于存放排好序的鍵值對  
  25. var newObj = {};
  26. //遍歷newkey數(shù)組
  27. for (var i = 0; i < newkey.length; i++) {
  28. //向新創(chuàng)建的對象中按照排好的順序依次增加鍵值對
  29. newObj[newkey[i]] = obj[newkey[i]];
  30. }
  31. //返回排好序的新對象
  32. return newObj;
  33. }
 

二、服務(wù)端功能編寫

由于初學(xué)SpringMVC,使用的方式不一定是最優(yōu)最好的,如有不妥善之處,請各位看官多多指教  思路:

通過過濾器攔截請求參數(shù),通過自定義參數(shù)包裝器對參數(shù)進(jìn)行解密。  在攔截器獲取請求的Token并生成服務(wù)器端Token進(jìn)行驗證。  對返回參數(shù)通過JSON轉(zhuǎn)換器進(jìn)行加密處理。

 1.重寫HttpServletRequestWrapper,在自定義的HttpServletRequestWrapper 中對參數(shù)進(jìn)行處理

 

  1. /**
  2. * Describe:請求參數(shù)包裝器 主要作用的過濾參數(shù)并解密
  3. * Created by 吳蜀黍 on 2018-08-07 09:37
  4. **/
  5. @Slf4j
  6. public class ParameterRequestWrapper extends HttpServletRequestWrapper {
  7.  
  8. private Map<String, String[]> params = new HashMap<>();
  9.  
  10. @SuppressWarnings("unchecked")
  11. public ParameterRequestWrapper(HttpServletRequest request) {
  12. // 將request交給父類,以便于調(diào)用對應(yīng)方法的時候,將其輸出,其實父親類的實現(xiàn)方式和第一種new的方式類似
  13. super(request);
  14. //將參數(shù)表,賦予給當(dāng)前的Map以便于持有request中的參數(shù)
  15. this.params.putAll(request.getParameterMap());
  16. this.modifyParameterValues();
  17. }
  18.  
  19. //重載一個構(gòu)造方法
  20. public ParameterRequestWrapper(HttpServletRequest request, Map<String, Object> extendParams) {
  21. this(request);
  22. addAllParameters(extendParams);//這里將擴(kuò)展參數(shù)寫入?yún)?shù)表
  23. }
  24.  
  25. private void modifyParameterValues() {//將parameter的值去除空格后重寫回去
  26.  
  27. //獲取加密數(shù)據(jù)
  28. String aesParameter = getParameter(Constants.NetWork.AES_DATA);
  29. log.debug("[modifyParameterValues]==========>加密數(shù)據(jù):{}", aesParameter);
  30. //解密
  31. String decryptParameter = null;
  32. try {
  33. decryptParameter = AesUtils.decrypt(aesParameter, Constants.AES.AES_KEY);
  34. log.debug("[modifyParameterValues]==========> 解密數(shù)據(jù):{}", decryptParameter);
  35. Map<String, Object> map = JSON.parseObject(decryptParameter);
  36. Set<String> set = map.keySet();
  37. for (String key : set) {
  38. params.put(key, new String[]{String.valueOf(map.get(key))});
  39. }
  40. aesFlag(true);
  41. } catch (CommonBusinessException e) {
  42. aesFlag(false);
  43. log.error("[modifyParameterValues]", e);
  44. log.debug("[modifyParameterValues]==========>", e);
  45. }
  46. }
  47.  
  48. /**
  49. * 解密成功標(biāo)志
  50. */
  51. private void aesFlag(boolean flag) {
  52. params.put(Constants.NetWork.AES_SUCCESS, new String[]{String.valueOf(flag)});
  53. }
  54.  
  55. @Override
  56. public Map<String, String[]> getParameterMap() {
  57. // return super.getParameterMap();
  58. return params;
  59. }
  60.  
  61. @Override
  62. public Enumeration<String> getParameterNames() {
  63. return new Vector<>(params.keySet()).elements();
  64. }
  65.  
  66. @Override
  67. public String getParameter(String name) {//重寫getParameter,代表參數(shù)從當(dāng)前類中的map獲取
  68. String[] values = params.get(name);
  69. if (values == null || values.length == 0) {
  70. return null;
  71. }
  72. return values[0];
  73. }
  74.  
  75. public String[] getParameterValues(String name) {//同上
  76. return params.get(name);
  77. }
  78.  
  79.  
  80. public void addAllParameters(Map<String, Object> otherParams) {//增加多個參數(shù)
  81. for (Map.Entry<String, Object> entry : otherParams.entrySet()) {
  82. addParameter(entry.getKey(), entry.getValue());
  83. }
  84. }
  85.  
  86.  
  87. public void addParameter(String name, Object value) {//增加參數(shù)
  88. if (value != null) {
  89. if (value instanceof String[]) {
  90. params.put(name, (String[]) value);
  91. } else if (value instanceof String) {
  92. params.put(name, new String[]{(String) value});
  93. } else {
  94. params.put(name, new String[]{String.valueOf(value)});
  95. }
  96. }
  97. }
  98. }

新建過濾器,在攔截器中調(diào)用自定義的參數(shù)包裝器

 

  1. /**
  2. * Describe:請求參數(shù)過濾器
  3. * Created by 吳蜀黍 on 2018-08-07 10:02
  4. **/
  5. @Slf4j
  6. public class ParameterFilter implements Filter {
  7. @Override
  8. public void init(FilterConfig filterConfig) throws ServletException {
  9. }
  10.  
  11. @Override
  12. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
  13. //使用自定義的參數(shù)包裝器對參數(shù)進(jìn)行處理
  14. ParameterRequestWrapper requestWrapper = new ParameterRequestWrapper((HttpServletRequest) servletRequest);
  15. filterChain.doFilter(requestWrapper, servletResponse);
  16. }
  17.  
  18. @Override
  19. public void destroy() {
  20. }
  21. }

web.xml中對過濾器進(jìn)行配置

 

  1. <!--過濾器-->
  2. <filter>
  3. <filter-name>parameterFilter</filter-name>
  4. <filter-class>com.xxx.xxx.config.filter.ParameterFilter</filter-class>
  5. </filter>
  6. <filter-mapping>
  7. <filter-name>parameterFilter</filter-name>
  8. <!-- 過濾所有以.json結(jié)尾的資源-->
  9. <url-pattern>*.json</url-pattern>
  10. </filter-mapping>

AES加解密操作

 

  1. /**
  2. * Describe:AES 加密
  3. * Created by 吳蜀黍 on 2018-08-03 17:47
  4. **/
  5. public class AesUtils {
  6. private static final String CHARSET_NAME = "UTF-8";
  7. private static final String AES_NAME = "AES";
  8. private static final String ALGORITHM = "AES/CBC/PKCS7Padding";
  9. private static final String IV = Constants.AES.AES_IV;
  10.  
  11. static {
  12. Security.addProvider(new BouncyCastleProvider());
  13. }
  14.  
  15. /**
  16. * 加密
  17. */
  18. public static String encrypt(@NotNull String content, @NotNull String key) throws CommonBusinessException {
  19. try {
  20. Cipher cipher = Cipher.getInstance(ALGORITHM);
  21. SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(CHARSET_NAME), AES_NAME);
  22. AlgorithmParameterSpec paramSpec = new IvParameterSpec(IV.getBytes());
  23. cipher.init(Cipher.ENCRYPT_MODE, keySpec, paramSpec);
  24. return ParseSystemUtil.parseByte2HexStr(cipher.doFinal(content.getBytes(CHARSET_NAME)));
  25. } catch (Exception ex) {
  26. throw new CommonBusinessException("加密失敗");
  27. }
  28. }
  29.  
  30. /**
  31. * 解密
  32. */
  33. public static String decrypt(@NotNull String content, @NotNull String key) throws CommonBusinessException {
  34. try {
  35. Cipher cipher = Cipher.getInstance(ALGORITHM);
  36. SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(CHARSET_NAME), AES_NAME);
  37. AlgorithmParameterSpec paramSpec = new IvParameterSpec(IV.getBytes());
  38. cipher.init(Cipher.DECRYPT_MODE, keySpec, paramSpec);
  39. return new String(cipher.doFinal(Objects.requireNonNull(ParseSystemUtil.parseHexStr2Byte(content))), CHARSET_NAME);
  40. } catch (Exception ex) {
  41. throw new CommonBusinessException("解密失敗");
  42. }
  43. }
  44.  
  45. }

2.新建攔截器,驗證Token以及解密的判斷

 

  1.  
  2. @Override
  3. public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
  4. //如果不是映射到方法直接通過
  5. if (!(handler instanceof HandlerMethod)) {
  6. return true;
  7. }
  8. //判斷參數(shù)包裝器中對請求參數(shù)的解密是否成功
  9. boolean aesSuccess = Boolean.parseBoolean(httpServletRequest.getParameter(Constants.NetWork.AES_SUCCESS));
  10. if (!aesSuccess) {
  11. this.sendMsg(Constants.NetWork.CODE_DECRYPTION_FAILURE, Constants.NetWork.MEG_AES_FAIL, httpServletResponse);
  12. return false;
  13. }
  14. //獲取客戶端上傳Token
  15. String token = httpServletRequest.getHeader(Constants.NetWork.TOKEN_HEAD_KEY);
  16. if (StringUtils.isNullOrEmpty(token)) {
  17. sendMsg(Constants.NetWork.CODE_TOKEN_INVALID, Constants.NetWork.MSG_TOKEN_EMPTY, httpServletResponse);
  18. return false;
  19. }
  20. //驗證Token的有效性
  21. if (!TokenUtils.verificationToken(token, httpServletRequest.getParameterMap())) {
  22. sendMsg(Constants.NetWork.CODE_TOKEN_INVALID, Constants.NetWork.MSG_TOKEN_INVALID, httpServletResponse);
  23. return false;
  24. }
  25. return true;
  26. }
  27.  
  28. /**
  29. * 驗證失敗 發(fā)送消息
  30. */
  31. private void sendMsg(String msgCode, String msg, HttpServletResponse httpServletResponse) throws IOException {
  32. httpServletResponse.setContentType("application/json; charset=utf-8");
  33. PrintWriter writer = httpServletResponse.getWriter();
  34. String jsonString = JSON.toJSONString(StandardResult.create(msgCode, msg));
  35. try {
  36. //對驗證失敗的返回信息進(jìn)行加密
  37. jsonString = AesUtils.encrypt(jsonString, Constants.AES.AES_KEY);
  38. } catch (CommonBusinessException e) {
  39. e.printStackTrace();
  40. jsonString = null;
  41. log.error("[sendMsg]", e);
  42. }
  43. writer.print(jsonString);
  44. writer.close();
  45. httpServletResponse.flushBuffer();
  46. }

在spring中對攔截器注冊

 

  1. <mvc:interceptors>
  2. <!-- 使用bean定義一個Interceptor,直接定義在mvc:interceptors根下面的Interceptor將攔截所有的請求 -->
  3. <mvc:interceptor>
  4. <!-- 攔截所有請求 -->
  5. <mvc:mapping path="/**"/>
  6. <!-- 需排除攔截的地址 -->
  7. <!--<mvc:exclude-mapping path="/"/>-->
  8. <bean class="com.xxx.xxx.config.interceptor.AsyncHandlerInterceptor"/>
  9. </mvc:interceptor>
  10. </mvc:interceptors>

Token的驗證

 

  1.  
  2. /**
  3. * Describe:Token幫助類
  4. * Created by 吳蜀黍 on 2018-08-04 14:48
  5. **/
  6. @Slf4j
  7. public class TokenUtils {
  8. /**
  9. * 驗證Token
  10. *
  11. * @param token 客戶端上傳Token
  12. * @param mapTypes 請求參數(shù)集合
  13. * @return boolean
  14. */
  15. public static boolean verificationToken(String token, Map mapTypes) {
  16. try {
  17. return StringUtils.saleEquals(token, getToken(mapTypes));
  18. } catch (UnsupportedEncodingException e) {
  19. log.error("[verificationToken]", e);
  20. return false;
  21. }
  22. }
  23.  
  24.  
  25. /**
  26. * 通過客戶端請求參數(shù)產(chǎn)生Token
  27. */
  28. private static String getToken(Map mapTypes) throws UnsupportedEncodingException {
  29. List<String> mapKes = new ArrayList<>();
  30. for (Object obj : mapTypes.keySet()) {
  31. String value = String.valueOf(obj);
  32. //去除參數(shù)中的加密相關(guān)key
  33. if (StringUtils.saleEquals(value, Constants.NetWork.AES_SUCCESS) ||
  34. StringUtils.saleEquals(value, Constants.NetWork.AES_DATA)) {
  35. break;
  36. }
  37. mapKes.add(value);
  38. }
  39. //排序key
  40. Collections.sort(mapKes);
  41. StringBuilder sb = new StringBuilder();
  42. for (String key : mapKes) {
  43. String value = ((String[]) mapTypes.get(key))[0];
  44. sb.append(value);
  45. }
  46. //加上時間戳,去除所有空格 進(jìn)行MD5加密
  47. String string = sb.append(DateUtils.getDateStr(DateUtils.FORMAT_YYYYMMDDHH)).toString().replace(" ", "");
  48. return MD5.getMD5(URLEncoder.encode(string, "UTF-8"));
  49. }
  50. }

3.對返回數(shù)據(jù)進(jìn)行加密處理,新建JSON轉(zhuǎn)換器繼承自阿里的FastJsonHttpMessageConverter

 

  1. /**
  2. * Describe:Json轉(zhuǎn)換器 將返回數(shù)據(jù)加密
  3. * Created by 吳蜀黍 on 2018-08-07 13:57
  4. **/
  5. @Slf4j
  6. public class JsonMessageConverter extends FastJsonHttpMessageConverter {
  7.  
  8. @Override
  9. protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException,
  10. HttpMessageNotWritableException {
  11. OutputStream out = outputMessage.getBody();
  12. try {
  13. String jsonString = JSON.toJSONString(object);
  14. log.debug("[writeInternal]======>返回明文數(shù)據(jù):{}" + jsonString);
  15. //對返回數(shù)據(jù)進(jìn)行AES加密
  16. jsonString = AesUtils.encrypt(jsonString, Constants.AES.AES_KEY);
  17. log.debug("[writeInternal]======>返回加密數(shù)據(jù):{}" + jsonString);
  18. out.write(jsonString.getBytes());
  19. } catch (CommonBusinessException e) {
  20. e.printStackTrace();
  21. log.error("[writeInternal]======>", e);
  22. }
  23. out.close();
  24. }
  25. }

spring中對JSON轉(zhuǎn)換器進(jìn)行配置

 

  1. <mvc:message-converters>
  2. <!--<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">-->
  3. <bean class="com.xxx.xxx.config.converter.JsonMessageConverter">
  4. <property name="supportedMediaTypes">
  5. <list>
  6. <value>text/html;charset=UTF-8</value>
  7. <value>application/json</value>
  8. <value>application/xml;charset=UTF-8</value>
  9. </list>
  10. </property>
  11. <property name="features">
  12. <list>
  13. <!-- 默認(rèn)的意思就是不配置這個屬性,配置了就不是默認(rèn)了 -->
  14. <!-- 是否輸出值為null的字段 ,默認(rèn)是false-->
  15. <value>WriteMapNullValue</value>
  16. <value>WriteNullNumberAsZero</value>
  17. <value>WriteNullListAsEmpty</value>
  18. <value>WriteNullStringAsEmpty</value>
  19. <value>WriteNullBooleanAsFalse</value>
  20. <value>WriteDateUseDateFormat</value>
  21. </list>
  22. </property>
  23. </bean>
  24. </mvc:message-converters>

以上就是微信小程序接口加密如何實現(xiàn)的開發(fā)文檔,更多小程序開發(fā)文檔可以關(guān)注網(wǎng)站。

HiShop小程序工具提供多類型商城/門店小程序制作,可視化編輯 1秒生成5步上線。通過拖拽、拼接模塊布局小程序商城頁面,所看即所得,只需要美工就能做出精美商城。更多小程序請查看:小程序商店


電話咨詢 預(yù)約演示 0元開店