JwtManageUtil.java 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. package com.miniframe.tools;
  2. import javax.crypto.SecretKey;
  3. import javax.crypto.spec.SecretKeySpec;
  4. import java.io.UnsupportedEncodingException;
  5. import java.security.MessageDigest;
  6. import java.security.NoSuchAlgorithmException;
  7. import java.sql.ClientInfoStatus;
  8. import java.util.Date;
  9. import java.util.HashMap;
  10. import java.util.Map;
  11. import java.util.UUID;
  12. import com.google.gson.Gson;
  13. import com.miniframe.config.Config;
  14. import com.miniframe.core.exception.BusinessException;
  15. import com.miniframe.core.ext.UtilTools;
  16. import io.jsonwebtoken.Claims;
  17. import io.jsonwebtoken.JwtBuilder;
  18. import io.jsonwebtoken.Jwts;
  19. import io.jsonwebtoken.SignatureAlgorithm;
  20. public class JwtManageUtil {
  21. public static class Constant {
  22. public static final int JWT_TTL = 24*60*60*1000; //millisecond
  23. public static String issuer="XI-TECH"; //颁发者 固定
  24. }
  25. /**
  26. * 由字符串生成加密key
  27. *
  28. * @return
  29. */
  30. private static SecretKey generalKey(String secretKey) {
  31. // 本地的密码解码
  32. //byte[] encodedKey = Base64.decodeBase64(secretKey);
  33. SecretKey key=null;
  34. try {
  35. byte[] encodedKey = secretKey.getBytes("utf-8");
  36. // 根据给定的字节数组使用AES加密算法构造一个密钥
  37. key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
  38. } catch (UnsupportedEncodingException e) {
  39. e.printStackTrace();
  40. }
  41. return key;
  42. }
  43. public static String getClientJWT(String uniqueid,String userId,String saltToken) throws Exception {
  44. JwtUser user = new JwtUser(userId,saltToken);
  45. String userJson = new Gson().toJson(user);
  46. String secretKey=generalSecret(uniqueid,userId); //服务给客户端的secret
  47. return JwtManageUtil.createClientJWT(uniqueid,secretKey, Constant.issuer, userJson, Constant.JWT_TTL,null);
  48. }
  49. /**
  50. * 创建jwt
  51. * @param uniqueid
  52. * @param issuer
  53. * @param userJson
  54. * @param ttlMillis
  55. * @return
  56. * @throws Exception
  57. */
  58. public static String createClientJWT(String uniqueid, String secretKey,String issuer, String userJson, long ttlMillis,Map<String, Object> claims) throws Exception {
  59. // 指定签名的时候使用的签名算法,也就是header那部分,jjwt已经将这部分内容封装好了。
  60. SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
  61. // 生成JWT的时间
  62. long nowMillis = System.currentTimeMillis();
  63. Date now = new Date(nowMillis);
  64. // 创建payload的私有声明(根据特定的业务需要添加,如果要拿这个做验证,一般是需要和jwt的接收方提前沟通好验证方式的)
  65. // Map<String, Object> claims = new HashMap<String, Object>();
  66. // claims.put("uid", "123456789");
  67. // 生成签名的时候使用的秘钥secret,切记这个秘钥不能外露哦。它就是你服务端的私钥,在任何场景都不应该流露出去。
  68. // 一旦客户端得知这个secret, 那就意味着客户端是可以自我签发jwt了。
  69. SecretKey key = generalKey(secretKey);
  70. // 下面就是在为payload添加各种标准声明和私有声明了
  71. JwtBuilder builder = Jwts.builder() // 这里其实就是new一个JwtBuilder,设置jwt的body
  72. .setId(uniqueid) // 设置jti(JWT ID):是JWT的唯一标识,根据业务需要,这个可以设置为一个不重复的值,主要用来作为一次性token,从而回避重放攻击。
  73. .setIssuedAt(now) // iat: jwt的签发时间
  74. .setIssuer(issuer) // issuer:jwt签发人
  75. .setSubject(userJson) // sub(Subject):代表这个JWT的主体,即它的所有人,这个是一个json格式的字符串,可以存放什么userid,roldid之类的,作为什么用户的唯一标志。
  76. .signWith(signatureAlgorithm, key); // 设置签名使用的签名算法和签名使用的秘钥
  77. if(claims!=null && !claims.isEmpty()){
  78. builder.setClaims(claims); // 如果有私有声明,一定要先设置这个自己创建的私有的声明,这个是给builder的claim赋值,一旦写在标准的声明赋值之后,就是覆盖了那些标准的声明的
  79. }
  80. // 设置过期时间
  81. if (ttlMillis >= 0) {
  82. long expMillis = nowMillis + ttlMillis;
  83. Date exp = new Date(expMillis);
  84. builder.setExpiration(exp);
  85. }
  86. return builder.compact();
  87. }
  88. /**
  89. * 解密jwt
  90. *
  91. * @param token
  92. * @return
  93. * @throws Exception
  94. */
  95. public static Claims parseJWT(String secret,String token) throws Exception {
  96. SecretKey key = generalKey(secret); //签名秘钥,和生成的签名的秘钥一模一样
  97. Claims claims = Jwts.parser() //得到DefaultJwtParser
  98. .setSigningKey(key) //设置签名的秘钥
  99. .parseClaimsJws(token).getBody(); //设置需要解析的jwt
  100. return claims;
  101. }
  102. public static String generalSecret(String serviceId,String userId){
  103. return getMD5(serviceId+"_"+getMD5(userId).toLowerCase()).toLowerCase(); //服务给客户端的secret
  104. }
  105. public static String getMD5( String s) {
  106. final char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  107. 'a', 'b', 'c', 'd', 'e', 'f'};
  108. MessageDigest mdInst;
  109. try {
  110. // 获得MD5摘要算法的 MessageDigest 对象
  111. mdInst = MessageDigest.getInstance("MD5");
  112. } catch (NoSuchAlgorithmException e) {
  113. e.printStackTrace();
  114. return "";
  115. }
  116. byte[] btInput = s.getBytes();
  117. // 使用指定的字节更新摘要
  118. mdInst.update(btInput);
  119. // 获得密文
  120. byte[] md = mdInst.digest();
  121. // 把密文转换成十六进制的字符串形式
  122. int length = md.length;
  123. char str[] = new char[length * 2];
  124. int k = 0;
  125. for (byte b : md) {
  126. str[k++] = hexDigits[b >>> 4 & 0xf];
  127. str[k++] = hexDigits[b & 0xf];
  128. }
  129. return new String(str);
  130. }
  131. public static class JwtUser{
  132. private String userId;
  133. private String userCrc;
  134. public String getUserCrc() {
  135. return userCrc;
  136. }
  137. public JwtUser(String userId,String uniqId) {
  138. this.userId = userId;
  139. this.userCrc=getMD5(userId+uniqId).toLowerCase();
  140. }
  141. public String getUserId() {
  142. return userId;
  143. }
  144. public void setUserId(String userId) {
  145. this.userId = userId;
  146. }
  147. }
  148. public static void main(String[] args) {
  149. String saltToken="12345678901234567890";
  150. String serviceId="b87cb209-e852-42bc-8d58-bc771a57b3eb"; //每个服务的唯一ID
  151. String userId="manager";
  152. JwtUser user = new JwtUser("manager",saltToken);
  153. String userJson = new Gson().toJson(user);
  154. String serviceToClientSecret=generalSecret(serviceId,userId); //服务给客户端的secret
  155. try {
  156. //客户端使用产生Token
  157. //String clientToken = JwtManageUtil.createClientJWT(serviceId,serviceToClientSecret, Constant.issuer, userJson, Constant.JWT_TTL,null);
  158. String clientToken=JwtManageUtil.getClientJWT(serviceId,"manager",saltToken);
  159. System.out.println("JWT:" + clientToken);
  160. //服务端解密验证
  161. System.out.println("\n解密\n");
  162. Claims c = JwtManageUtil.parseJWT(serviceToClientSecret,clientToken);
  163. System.out.println(c.getId()); //唯一ID
  164. System.out.println(c.getIssuer()); //颁发者
  165. System.out.println(c.getSubject()); //客户身份信息
  166. System.out.println(c.getIssuedAt()); //token产生时间
  167. System.out.println(c.getExpiration()); //token到期时间
  168. //System.out.println(c.getNotBefore());
  169. //System.out.println(c.get("uid", String.class)); //私有数据
  170. } catch (Exception e) {
  171. e.printStackTrace();
  172. }
  173. }
  174. }