java验证消息的确来自微信服务器

package com.connecthzero.accesstoken.controller.v2;

import com.connecthzero.accesstoken.domain.SqlParams;

import com.connecthzero.accesstoken.service.WxCheckSignatureService;

import io.swagger.annotations.ApiImplicitParam;

import io.swagger.annotations.ApiImplicitParams;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.RestController;

/**

* description

*

* @author changbao.pei 2020/03/26 18:13

*/

@RestController

@RequestMapping("/api/v2")

public class WeChatController {

static final  Stringuser ="[email protected]";

static final  Stringpass ="170502";

@Autowired

    private SqlParamssqlParams;

//记录器

    Loggerlogger = LoggerFactory.getLogger(WeChatController.class);

@GetMapping("/TokenCheck")

@ApiImplicitParams({

@ApiImplicitParam(paramType ="query", dataType ="string", name ="signature",required =true ,value ="微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。"),

@ApiImplicitParam(paramType ="query", dataType ="string", name ="timestamp",required =true ,value ="时间戳"),

@ApiImplicitParam(paramType ="query", dataType ="string", name ="nonce",required =true ,value ="随机数"),

@ApiImplicitParam(paramType ="query", dataType ="string", name ="echostr",required =true ,value ="随机字符串")

})

public String checkToken(@RequestParam("signature") String signature,@RequestParam("timestamp") String timestamp,

@RequestParam("nonce") String nonce,@RequestParam("echostr") String echostr) {

return  WxCheckSignatureService.checkSignature(signature, timestamp, nonce,echostr);

}

}


package com.connecthzero.accesstoken.service;

import com.connecthzero.accesstoken.controller.v2.WeChatController;

import com.connecthzero.accesstoken.dto.ShaUtil;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Value;

/**

* description

*

* @author changbao.pei 2021/04/01 13:19

*/

public class WxCheckSignatureService {

@Value("${wx.token}")

/**

    * @Description  进行签名认证

    * @param signature 微信加密签名

    * @param timestamp 时间戳

    * @param nonce 随机数

    * @param echostr 随机字符串

    * @return java.lang.String

*/

    public static String checkSignature(String signature, String timestamp, String nonce, String echostr) {

String token ="changbao";

//记录器

        Logger logger = LoggerFactory.getLogger(WeChatController.class);

// 1.将token、timestamp、nonce三个参数进行字典序排序

        logger.info("signature:{},token:{},timestamp:{},nonce:{}",signature,token,timestamp,nonce);

String tmpStr = ShaUtil.getSHA1(token,  timestamp,  nonce);

//TODO 进行对比

        logger.info("随机字符串echostr:{}",echostr);

logger.info("tmpStr:{}",tmpStr);

if (tmpStr.equals(signature.toUpperCase())) {

return echostr;

}

return null;

}

}


package com.connecthzero.accesstoken.dto;

import com.connecthzero.accesstoken.controller.v2.WeChatController;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

import java.util.Arrays;

/**

* description

*

* @author changbao.pei 2021/04/01 13:22

*/

public class ShaUtil {

/**

    * @Description  用SHA1算法验证Token

    * @param token url相关的token

    * @param timestamp 时间戳

    * @param nonce 随机数

    * @return java.lang.String

*/

    public static StringgetSHA1(String token, String timestamp, String nonce){

//记录器

        Logger logger = LoggerFactory.getLogger(WeChatController.class);

String[] arr =new String[] { token, timestamp, nonce };

Arrays.sort(arr);

//TODO 2. 将三个参数字符串拼接成一个字符串进行sha1加密

        StringBuilder content =new StringBuilder();

for (int i =0; i < arr.length; i++) {

content.append(arr[i]);

}

MessageDigest md =null;

String tmpStr =null;

try {

md = MessageDigest.getInstance("SHA-1");

// 将三个参数字符串拼接成一个字符串进行sha1加密

            byte[] digest = md.digest(content.toString().getBytes());

tmpStr =byteToStr(digest);

}catch (NoSuchAlgorithmException e) {

logger.info("错误信息:{}",e.getMessage());

}

return tmpStr;

}

/**

    * @Description 将字节数组转换为十六进制字符串

    * @param byteArray

    * @return java.lang.String

*/

    private static String byteToStr(byte[] byteArray) {

StringBuilder strDigest =new StringBuilder();

for (int i =0; i < byteArray.length; i++) {

strDigest.append(byteToHexStr(byteArray[i]));

}

return strDigest.toString();

}

/**

    * @Description  将字节转换为十六进制字符串

    * @param mByte

    * @return java.lang.String

*/

    private static String byteToHexStr(byte mByte) {

char[]Digit= {'0','1','2','3','4','5','6','7','8','9','A',

'B','C','D','E','F' };

char[] tempArr =new char[2];

tempArr[0] = Digit[(mByte >>>4) &0X0F];

tempArr[1] = Digit[mByte &0X0F];

String s =new String(tempArr);

return s;

}

}


application.yml配置

wx:token:xxxxx

你可能感兴趣的:(java验证消息的确来自微信服务器)