Browse Source

更新JWT算法

master
xyiege 4 years ago
parent
commit
974f90c37f
  1. 10
      pom.xml
  2. 114
      src/main/java/cn/chjyj/szwh/utils/ApiTokenUtils.java
  3. 128
      src/main/java/cn/chjyj/szwh/utils/SignUtils.java
  4. 3
      szwh.iml

10
pom.xml

@ -110,11 +110,11 @@
</dependency>
<!-- jwt-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<!--<dependency>-->
<!--<groupId>io.jsonwebtoken</groupId>-->
<!--<artifactId>jjwt</artifactId>-->
<!--<version>0.9.1</version>-->
<!--</dependency>-->
<!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
<dependency>
<groupId>com.auth0</groupId>

114
src/main/java/cn/chjyj/szwh/utils/ApiTokenUtils.java

@ -1,114 +0,0 @@
package cn.chjyj.szwh.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.binary.Base64;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* token 生成与验证工具
*/
public class ApiTokenUtils {
/**
* @param iss 从天朗获取
* @param pri 从天朗获取
* @param exp token有效期
* @return
* @throws Exception
*/
public static String getToken(String iss, String pri, Long exp) throws Exception {
Date date = new Date(System.currentTimeMillis());
return Jwts
.builder()
.signWith(SignatureAlgorithm.RS256, getPrivateKey(pri))
.setIssuer(iss)
.setExpiration(new Date(date.getTime() + exp))
.setIssuedAt(date)
.compact();
}
/**
* 生产token
* @param iss 发行者
* @param pri 私钥
* @param exp 过期时间 long型
* @param claims 验证参数
* @return
* @throws Exception
*/
public static String getToken(String iss, String pri, Long exp, Map<String, Object> claims) throws Exception {
Date date = new Date(System.currentTimeMillis());
return Jwts
.builder()
.setClaims(claims)
.signWith(SignatureAlgorithm.RS256, getPrivateKey(pri))
.setIssuer(iss)
.setExpiration(new Date(date.getTime() + exp))
.setIssuedAt(date)
.compact();
}
/**
* 解析jwt token
* 公钥解密
* @param jwt
* @return
*/
public static Claims parseJWT(String jwt,String pubkey) throws Exception {
return Jwts.parser()
.setSigningKey(pubkey)
.parseClaimsJws(jwt)
.getBody();
}
/**
* 抽取公钥
* @param publicKey
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
String publicKeyPEM = publicKey.replace("-----BEGIN PUBLIC KEY-----\r\n", "");
publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");
Base64 b64 = new Base64();
byte [] decoded = b64.decode(publicKeyPEM);
X509EncodedKeySpec spec =
new X509EncodedKeySpec(decoded);
KeyFactory kf = KeyFactory.getInstance("RSA");
return (RSAPublicKey) kf.generatePublic(spec);
}
/**
* 抽取私钥
* @param privateKey
* @return
* @throws Exception
*/
public static RSAPrivateKey getPrivateKey(String privateKey) throws Exception {
String privKeyPEM = privateKey.replace("-----BEGIN PRIVATE KEY-----\r\n", "");
privKeyPEM = privKeyPEM.replace("-----END PRIVATE KEY-----", "");
Base64 b64 = new Base64();
byte [] decoded = b64.decode(privKeyPEM);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
KeyFactory kf = KeyFactory.getInstance("RSA");
return (RSAPrivateKey)kf.generatePrivate(spec);
}
}

128
src/main/java/cn/chjyj/szwh/utils/SignUtils.java

@ -3,11 +3,24 @@ package cn.chjyj.szwh.utils;
import cn.chjyj.szwh.constant.ChConstant;
import cn.chjyj.szwh.exception.ChException;
import com.auth0.jwt.JWT;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@ -88,22 +101,115 @@ public class SignUtils {
public static String createSign(String type) {
String signStr = "";//签名后的字符
long exp = 5 * 60 * 1000l; //5分钟超时
Date date = new Date(System.currentTimeMillis());
// 日历获取当前秒
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND,(int)exp);
Date expireDate = cal.getTime();
// 证书信息
Map xmap = getTypeMap(type);
String private_key_path = (String) xmap.get("private_key");//私钥存放位置
// 填充
Map<String,String> payload= new HashMap<>();
payload.put("iss",(String)xmap.get("pem_token"));
//payload.put("exp",expireDate.toString()); //过期
payload.put("iat",cal.getTime().toString());//发行日期
// 如果是用户
if("user_real".equals(type)){
payload.put("aud","BD84DD42A7234B05B0C5D11616132AC4");
}
//私钥存放位置
String private_key_path = (String) xmap.get("private_key");
try {
// 私钥
String prinote = SzFileUtils.getKeyFromFile(ChConstant.WORK_DIR + "/" + private_key_path);
signStr = Jwts.builder()
.signWith(SignatureAlgorithm.RS256, prinote)
.setIssuer((String) xmap.get("pem_token"))
.setExpiration(new Date(date.getTime() + exp))
.setIssuedAt(date)
.compact();
RSAPrivateKey rsaPrivateKey = getPrivateKey(ChConstant.WORK_DIR + "/" + private_key_path);
JWTCreator.Builder builder = JWT.create();
// 头部信息
Map<String,Object> a = new HashMap<>(payload);
builder.withHeader(a);
// 构建payload
// stream 流式
payload.forEach((k,v)->builder.withClaim(k,v));
// 过期时间
builder.withExpiresAt(expireDate);
// 签名
signStr = builder.sign(Algorithm.RSA256(null,rsaPrivateKey));
return signStr;
} catch (Exception ex) {
log.error(ex.getCause());
throw new ChException("私钥证书不存在");
}
}
/**
* 解析token
* @param tokenStr
* @param type
* @return
*/
public static Map<String, Claim> resolveJwtToken(String tokenStr,String type){
try{
// 证书信息
Map xmap = getTypeMap(type);
// 公钥证书路径
String pubkey=(String) xmap.get("public_key");
// 公钥证书
RSAPublicKey rsaPublicKey = getPublicKey(pubkey);
// 解析对象,算法与加密时候一致
JWTVerifier jwtVerifier = JWT.require(Algorithm.RSA256(rsaPublicKey,null)).build();
//解析指定token
DecodedJWT decodedJWT= jwtVerifier.verify(tokenStr);
//获取claim信息
Map<String,Claim> pcmap = decodedJWT.getClaims();
return pcmap;
}catch (Exception ex){
log.error(ex.getStackTrace());
throw new ChException("公钥证书不存在");
}
}
/**
* 抽取公钥
* @param publicKey
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
String publicKeyPEM = publicKey.replace("-----BEGIN PUBLIC KEY-----\r\n", "");
publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");
Base64 b64 = new Base64();
byte [] decoded = b64.decode(publicKeyPEM);
X509EncodedKeySpec spec =
new X509EncodedKeySpec(decoded);
KeyFactory kf = KeyFactory.getInstance("RSA");
return (RSAPublicKey) kf.generatePublic(spec);
}
/**
* 抽取私钥
* @param privateKey
* @return
* @throws Exception
*/
public static RSAPrivateKey getPrivateKey(String privateKey) throws Exception {
String privKeyPEM = privateKey.replace("-----BEGIN PRIVATE KEY-----\r\n", "");
privKeyPEM = privKeyPEM.replace("-----END PRIVATE KEY-----", "");
Base64 b64 = new Base64();
byte [] decoded = b64.decode(privKeyPEM);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
KeyFactory kf = KeyFactory.getInstance("RSA");
return (RSAPrivateKey)kf.generatePrivate(spec);
}
}

3
szwh.iml

@ -120,10 +120,9 @@
<orderEntry type="library" name="Maven: com.alibaba:druid:1.2.6" level="project" />
<orderEntry type="library" name="Maven: org.apache.httpcomponents:httpclient:4.5.9" level="project" />
<orderEntry type="library" name="Maven: org.apache.httpcomponents:httpcore:4.4.15" level="project" />
<orderEntry type="library" name="Maven: io.jsonwebtoken:jjwt:0.9.1" level="project" />
<orderEntry type="library" name="Maven: com.auth0:java-jwt:3.8.3" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.13.3" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.13.3" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-core:2.13.3" level="project" />
<orderEntry type="library" name="Maven: com.auth0:java-jwt:3.8.3" level="project" />
</component>
</module>
Loading…
Cancel
Save