package cn.sharing.www.controller;
import cn.sharing.www.util.HashUtil;
import cn.sharing.www.util.MD5Util;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.security.provider.MD5;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
@RestController
public class WechatController {
private static final String TOKEN = "shenzhenchuanyue";
@GetMapping("/wx")
public String checkServer(
@RequestParam(name = "signature") String signature,
@RequestParam(name = "echostr") String echostr,
@RequestParam(name = "timestamp") String timestamp,
@RequestParam(name = "nonce") String nonce, HttpServletRequest request) {
List<String> list = new ArrayList<>();
list.add(TOKEN);
list.add(timestamp);
list.add(nonce);
Collections.sort(list);
StringBuilder builder = new StringBuilder();
list.forEach((str)-> builder.append(str));
String hashCode = HashUtil.hash(builder.toString(),"sha-1");
System.out.println("hashCode = " + hashCode);
System.out.println("signature = " + signature);
return Objects.equals(hashCode,signature)? echostr: null;
}
}
package cn.sharing.www.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class HashUtil {
/**
* 计算字符串的hash值
* @param string 明文
* @param algorithm 算法名
* @return 字符串的hash值
*/
public static String hash(String string, String algorithm) {
if (string.isEmpty()) {
return "";
}
MessageDigest hash = null;
try {
hash = MessageDigest.getInstance(algorithm);
byte[] bytes = hash.digest(string.getBytes("UTF-8"));
String result = "";
for (byte b : bytes) {
String temp = Integer.toHexString(b & 0xff);
if (temp.length() == 1) {
temp = "0" + temp;
}
result += temp;
}
return result;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}
/**
* 计算文件的hash值
* @param file 文件File
* @param algorithm 算法名
* @return 文件的hash值
*/
public static String hash(File file, String algorithm) {
if (file == null || !file.isFile() || !file.exists()) {
return "";
}
FileInputStream in = null;
String result = "";
byte buffer[] = new byte[0124];
int len;
try {
MessageDigest hash = MessageDigest.getInstance(algorithm);
in = new FileInputStream(file);
while ((len = in.read(buffer)) != -1) {
hash.update(buffer, 0, len);
}
byte[] bytes = hash.digest();
for (byte b : bytes) {
String temp = Integer.toHexString(b & 0xff);
if (temp.length() == 1) {
temp = "0" + temp;
}
result += temp;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(null!=in){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
}
注:加密工具类复制自某个博客的,忘记链接了。