step1、引入jwt依赖
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
step2、直接贴代码
//生成jwt的参数类
package tt.com;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @author: songgt
* @date: 2019-03-05 15:10
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class JwtObj implements Serializable {
private static final long serialVersionUID = 1691489461127248816L;
private String taxNo;
private String cusName;
private String machineNo;
private long expires;
}
//JwtUtil类
package tt.util;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import tt.com.JwtObj;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
/**
* @author: songgt
* @date: 2019-03-05 14:53
*/
public class JwtUtil {
private final static String base64Secret = "szaisinoMDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=";
/**
* 定义泛型方法,方便传入任何类型入参对象
*/
public static <T>String createJwt(T obj){
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
//生成签名密钥
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Secret);
Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
//构造jwt
JwtObj jwtObj = (JwtObj) obj;
JwtBuilder builder = Jwts.builder().setHeaderParam("type","jwt")
.claim("taxNo",jwtObj.getTaxNo())
.claim("cusName",jwtObj.getCusName())
.claim("machineNo",jwtObj.getMachineNo())
.signWith(signatureAlgorithm,signingKey);
//添加Token过期时间
if (jwtObj.getExpires() >= 0) {
long expMillis = nowMillis + jwtObj.getExpires();
Date exp = new Date(expMillis);
builder.setExpiration(exp).setNotBefore(now);
}
//生成jwt
return builder.compact();
}
/**
* 解析jwt
* @param jsonWebToken
* @return
*/
public static Claims parseJWT(String jsonWebToken) {
try {
Claims claims = Jwts.parser()
.setSigningKey(DatatypeConverter.parseBase64Binary(base64Secret))
.parseClaimsJws(jsonWebToken).getBody();
return claims;
} catch (Exception ex) {
return null;
}
}
public static void main(String[] args) {
JwtObj jwtObj = new JwtObj();
jwtObj.setCusName("xxx有限公司");
jwtObj.setTaxNo("45623598205641980");
jwtObj.setMachineNo("0");
jwtObj.setExpires(300000);
String jwtStr = createJwt(jwtObj);
System.out.println("JwtToken是:"+jwtStr);
System.out.println();
long timestamp = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
try {
String aesStr = AesUtil.encrypt(jwtStr, String.format("%016d",timestamp));
System.out.println("AES加密:"+aesStr);
System.out.println();
String aesDeStr = AesUtil.decrypt(aesStr, String.format("%016d",timestamp));
System.out.println("AES解密:"+aesDeStr);
jwtStr = aesDeStr;
}catch (Exception e){
e.printStackTrace();
}
System.out.println();
Claims claims = parseJWT(jwtStr);
System.out.println(claims.get("taxNo"));
System.out.println(claims.get("cusName"));
System.out.println(claims.get("machineNo"));
}
}
//AES加解密类,确保token的保密性
package tt.util;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.UUID;
/**
* @author: songgt
* @date: 2018-11-13 18:14
*/
public class AesUtil {
// private static String password = "1234567812345678";
/**
* AES加密【AES/ECB/PKCS5Padding】
* @param content
* @return
* @throws Exception
*/
public static String encrypt(String content,String password) throws Exception{
byte[] bysKey = password.getBytes("UTF-8");
SecretKeySpec key = new SecretKeySpec(bysKey, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
byte[] byteContent = content.getBytes("UTF-8");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(byteContent);
return Base64.encodeBase64String(result);
}
/**
* AES解密【AES/ECB/PKCS5Padding】
* @param content
* @return
* @throws Exception
*/
public static String decrypt(String content,String password)throws Exception{
byte[] bContent = Base64.decodeBase64(content);
byte[] bysKey = password.getBytes("UTF-8");
SecretKeySpec key = new SecretKeySpec(bysKey, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] result = cipher.doFinal(bContent);
return new String(result,"UTF-8");
}
private static String createPassWord(){
int hashCodeV = UUID.randomUUID().toString().hashCode();
if (hashCodeV < 0) {
hashCodeV = -hashCodeV;
}
return String.format("%016d", hashCodeV);
}
public static void main(String[] args) {
try {
String password = createPassWord();
String encryptStr = encrypt("guang涛",password);
System.out.println(encryptStr);
System.out.println(decrypt(encryptStr,password));
} catch (Exception e) {
e.printStackTrace();
}
}
}
网友评论