SignUtils.java 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package com.qs.mp.handler.auth;
  2. import com.qs.mp.common.utils.sign.Md5Utils;
  3. import java.io.UnsupportedEncodingException;
  4. import java.security.MessageDigest;
  5. import java.security.NoSuchAlgorithmException;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. import org.springframework.beans.factory.annotation.Value;
  9. /**
  10. * 签名工具类
  11. * @author duota
  12. *
  13. */
  14. public class SignUtils {
  15. protected static Logger logger = LoggerFactory.getLogger(SignUtils.class);
  16. @Value("${sign.md5key}")
  17. private static String md5key = "3Jr8S1K18rcC1wAfv8";
  18. public static String md5(String string) {
  19. byte[] hash;
  20. try {
  21. hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
  22. } catch (UnsupportedEncodingException e) {
  23. throw new RuntimeException("UTF-8 is unsupported", e);
  24. } catch (NoSuchAlgorithmException e) {
  25. throw new RuntimeException("MessageDigest不支持MD5Util", e);
  26. }
  27. StringBuilder hex = new StringBuilder(hash.length * 2);
  28. for (byte b : hash) {
  29. if ((b & 0xFF) < 0x10)
  30. hex.append("0");
  31. hex.append(Integer.toHexString(b & 0xFF));
  32. }
  33. return hex.toString();
  34. }
  35. public static boolean verifySign(String sign,String body,String timestamp) {
  36. String l = body+ "nonce"+ timestamp + md5key;
  37. logger.debug("sign str:"+l);
  38. String mySign = Md5Utils.hash(l);
  39. logger.debug("mySign:"+mySign+" sign:"+sign);
  40. return mySign.equals(sign);
  41. }
  42. }