1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| import com.google.common.base.Joiner; import com.google.common.collect.Lists; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*;
import java.security.MessageDigest; import java.util.ArrayList; import java.util.Collections; @Controller public class MainController { private static final Log log = LogFactory.getLog(MainController.class);
@Value("${token}") private String token;
@RequestMapping(value = "/index", method = RequestMethod.GET, produces = "text/html;charset=UTF-8") public @ResponseBody ResponseEntity<String> auth(@RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp, @RequestParam("nonce") String nonce, @RequestParam("echostr") String echostr) throws Exception { log.info("wechat auth start"); log.info(String.format("signature:%s, timestamp:%s, nonce:%s, echostr:%s", signature, timestamp, nonce, echostr));
if (wechatAuth(signature, timestamp, nonce)) { log.info("wechat auth success"); return new ResponseEntity<String>(echostr, HttpStatus.OK); }
log.info("wechat auth failed"); return new ResponseEntity<String>("wechat auth failed.", HttpStatus.BAD_REQUEST); }
private boolean wechatAuth(String signature, String timestamp, String nonce) { ArrayList<String> strings = Lists.newArrayList(token, timestamp, nonce); log.info(String.format("before sort array:%s", strings)); Collections.sort(strings); log.info(String.format("after sort array:%s", strings));
String groupString = Joiner.on("").join(strings); log.info(String.format("groupString string:%s", groupString));
String result = sha1(groupString); log.info(String.format("sha1:%s", result)); boolean compareResult = result.equals(signature.toUpperCase()); log.info(String.format("compare result:%b", compareResult)); return compareResult; }
private String sha1(String s) { try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest();
StringBuilder hexString = new StringBuilder(); for (byte aMessageDigest : messageDigest) { hexString.append(String.format("%02X", 0xFF & aMessageDigest)); } return hexString.toString(); } catch (Exception e) { throw new RuntimeException("sha1 failed"); } } }
|