首页 > 编程语言 >java工具类-jwt-RSA256算法加密

java工具类-jwt-RSA256算法加密

时间:2022-11-24 16:26:32浏览次数:41  
标签:java String RSA256 privateKey jwt return import public

  1. 加密数据(用户信息)
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 + '\'' +
                '}';
    }
}

  1. 生成公钥和私钥工具
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;
    }*/
}

  1. 加密验证工具
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;
        }

    }
}

  1. 存储公钥私钥对象
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;
    }
}

  1. 测试类
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

运行结果

在这里插入图片描述

标签:java,String,RSA256,privateKey,jwt,return,import,public
From: https://www.cnblogs.com/zryMvs/p/16922232.html

相关文章

  • java常用类之Random
    packagecom.Lucky.OftenClass;importjava.util.Random;/***Random:随机类**注意点:Math.Random()底层调用的是Random的nextDouble方法*/publicclassR......
  • java常用类之枚举
    packagecom.Lucky.OftenClass;/*枚举定义*/publicenumEnumClass{//枚举内容男,女,girl,boy}packagecom.Lucky.OftenClass;publicclass......
  • java包装类
    packagecom.Lucky.OftenClass;/*包装类:1.为了解决现实中将基本数据类型转换成对象,以便操作【java。lang】2.实现字符串与基本数据类型之间的转换......
  • java常用类之Math
    packagecom.Lucky.OftenClass;/*Math1类:*/publicclassMathCalss{publicstaticvoidmain(String[]args){System.out.println(Math.PI);......
  • 数据结构与算法java实现
    什么是数组?(1)数组是计算机中最基本的数据结构之一,我们会用一些名为索引的数字来标识每项数据在数组中的位置。(2)大多数编程语言中索引是从0开始的。(3)数组在内存中是存在......
  • java异常
       packagecom.Lucky.oop;importjava.io.IOException;importstaticcom.Lucky.oop.DefindsException.Add;/*异常:throwAble:error与exce......
  • java构造器
    构造器:packagecom.Lucky.oop;publicclassconstructor{/*构造器:1.创建完成一个类之后,会自动再创建一个无参构造器【不显示】......
  • java map entrySet() 应用
    javamapentrySet()应用:publicbooleanhasPermission(Map<String,Object>map){booleanflag=false;if(StringHelper.IsEmptyOrNull(map.ge......
  • java接口
    packagecom.Lucky.oop.InterfaceUnion;/*接口:1.可以实现多继承【指的是实现】2.接口中只能存在定义的方法3.修饰符默认【只能】是pu......
  • 第三节:常用解决方案剖析(Excel导出、工作单元、领域事件、JWT回收问题等)
    一.Excel导出1.效果  2.前端剖析  3.接口剖析      二.        三.         !作       者......