- 加密数据(用户信息)
package testJWT;
/**
* @author ZRY
* @version 1.0
*/
public class User {
//用户id
private int id;
//用户名称
private String name;
//用户密码
private String pwd;
//用户角色
private String role;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
", role='" + role + '\'' +
'}';
}
}
- 生成公钥和私钥工具
package testJWT;
import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;
import javax.annotation.Resource;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Map;
import java.util.UUID;
/**
* @author ZRY
* @version 1.0
*/
public class RSA256Util {
//数字签名
public static final String KEY_ALGORITHM = "RSA";
//RSA密钥长度
public static final int KEY_SIZE = 1024;
//唯一的密钥实例
private static RSA256Key rsa256Key=new RSA256Key();
/**
* 初始化密钥,生成公钥和私钥
* @param seed1 种子数
* @return 公钥和私钥的键值对
* @throws Exception
*/
public static RSA256Key initKey(String seed1) throws Exception{
BASE64Encoder encoder = new BASE64Encoder();
//第一次校验:单例模式只需要创建一次实例,若存在实例,不需要继续竞争锁,
if (rsa256Key.getPrivateKey()==null || rsa256Key.getPublicKey()==null){
synchronized (RSA256Key.class){
//第二次校验:防止锁竞争中自旋的线程,拿到系统资源时,重复创建实例
if (rsa256Key.getPrivateKey()==null || rsa256Key.getPublicKey()==null){
byte[] seed = seed1.getBytes();
//实例化密钥生成器
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
//初始化密钥生成器
keyPairGenerator.initialize(KEY_SIZE, new SecureRandom(seed));
//生成密钥对
KeyPair keyPair = keyPairGenerator.generateKeyPair();
//公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// System.out.println(encoder.encodeBuffer(publicKey.getEncoded()));
//私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
// System.out.println(encoder.encodeBuffer(privateKey.getEncoded()));
rsa256Key.setPrivateKey(privateKey);
rsa256Key.setPublicKey(publicKey);
}
}
}
return rsa256Key;
}
/**
* 重载初始化密钥方法,随机生成种子数
* @return
* @throws Exception
*/
public static RSA256Key initKey() throws Exception{
return initKey(UUID.randomUUID().toString());
}
/* *//**
* 将公钥字符串转化为key
* @param publicKey 公钥字符串
* @return 公钥
* @throws Exception
*//*
private static PublicKey getPublicKey(String publicKey) throws Exception{
BASE64Decoder decoder = new BASE64Decoder();
byte[] bytes = decoder.decodeBuffer(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey key = keyFactory.generatePublic(keySpec);
return key;
}
*//**
* 将私钥字符串转化为key
* @param privateKey 私钥字符串
* @return 私钥
* @throws Exception
*//*
private static PrivateKey getPrivateKey(String privateKey) throws Exception{
BASE64Decoder decoder = new BASE64Decoder();
byte[] bytes = decoder.decodeBuffer(privateKey);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey key = keyFactory.generatePrivate(keySpec);
return key;
}*/
}
- 加密验证工具
package testJWT;
import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;
/**
* jwt-rs256算法
* 公钥加密
* 私钥解密
* @author ZRY
* @version 1.0
*/
public class JWTUtil {
//有效期为
public static final Long JWT_TTL = 60 * 60 *1000L;// 60 * 60 *1000 一个小时
/**
* 公钥加密
* @param user 未加密数据
* @param privateKey 私钥
* @return encaypt 加密数据
* @throws Exception
*/
public static String createToken(User user,RSAPrivateKey privateKey) throws Exception{
// 生成私钥
// RSAPrivateKey privateKey = RSA256Util.initKey().getPrivateKey();
//加密
Algorithm algorithm = Algorithm.RSA256(privateKey);
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
long expMillis = nowMillis + JWT_TTL;
Date expDate = new Date(expMillis);
String token = JWT.create()
//签发人
.withIssuer("z")
//接受者
.withAudience(user.toString())
//签发时间
.withIssuedAt(now)
//过期时间
.withExpiresAt(expDate)
.withClaim("data",JSON.toJSONString(user))
.sign(algorithm);
return token;
}
/**
* 解析
* @param token 目标token
* @return 校验结果
*/
public static boolean verify(String token,RSAPublicKey publicKey){
/* //打印token中内容
String payload = String.valueOf(JWT.decode(token).getClaims());
System.out.println(payload);*/
Algorithm algorithm = Algorithm.RSA256(publicKey);
JWTVerifier verifier = JWT.require(algorithm).withIssuer("z").build();
// System.out.println(verifier);
try {
DecodedJWT verify = verifier.verify(token);
return true;
} catch (JWTVerificationException e) {
return false;
}
}
}
- 存储公钥私钥对象
package testJWT;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
/**
* RSA256
* @author ZRY
* @version 1.0
*/
public class RSA256Key {
private RSAPublicKey publicKey;
private RSAPrivateKey privateKey;
public RSA256Key() {
}
public RSA256Key(RSAPublicKey publicKey, RSAPrivateKey privateKey) {
this.publicKey = publicKey;
this.privateKey = privateKey;
}
public RSAPublicKey getPublicKey() {
return publicKey;
}
public void setPublicKey(RSAPublicKey publicKey) {
this.publicKey = publicKey;
}
public RSAPrivateKey getPrivateKey() {
return privateKey;
}
public void setPrivateKey(RSAPrivateKey privateKey) {
this.privateKey = privateKey;
}
}
- 测试类
package testJWT;
import Decoder.BASE64Encoder;
import com.sun.org.apache.xml.internal.security.Init;
import java.security.interfaces.RSAKey;
import java.util.Map;
/**
* @author ZRY
* @version 1.0
*/
public class main {
public static void main(String[] args) {
BASE64Encoder encoder = new BASE64Encoder();
User user = new User();
user.setId(1);
user.setName("ll");
user.setPwd("124");
user.setRole("1");
try {
RSA256Key rsa256Key = RSA256Util.initKey();
// System.out.println(encoder.encodeBuffer(rsa256Key.getPrivateKey().getEncoded()));
String token = JWTUtil.createToken(user, rsa256Key.getPrivateKey());
System.out.println(token);
boolean verify = JWTUtil.verify(token,rsa256Key.getPublicKey());
System.out.println(verify);
} catch (Exception e) {
e.printStackTrace();
}
}
}
项目所需jar包
- fastjson-1.2.33.jar
- jackson-annotations-2.9.0.jar
- jackson-core-2.9.5.jar
- jackson-databind-2.9.5.jar
- java-jwt-4.0.0.jar