创建RSA 秘钥和私钥生成jwt token

1、pom依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.2.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-security</artifactId>
        <version>2.2.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.12.5</version>
    </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.16</version> 
        </dependency>
</dependencies>

2、生成公私钥,私钥生成token

package com.nancal.util;

import com.nancal.vo.KeyPairVO;
import io.jsonwebtoken.Jwts;
import org.apache.tomcat.util.codec.binary.Base64;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class RSAKeyUtils {
    /**
     * token过期时间
     * 24小时
     */
    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;

    /**
     *
     */
    private final static int KEY_SIZE = 2048;

    /**
     * 获取秘钥对对象
     *
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static KeyPairVO getKeyPairVO() throws NoSuchAlgorithmException {
        // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥对生成器
        keyPairGenerator.initialize(KEY_SIZE, new SecureRandom());
        // 生成一个密钥对,保存在keyPair中
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        // 得到公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        String publicKeyStr = Base64.encodeBase64String(publicKey.getEncoded());
        // 得到私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        String privateKeyStr = Base64.encodeBase64String(privateKey.getEncoded());
        Map<String, String> payLoadMap = new HashMap<>();
        payLoadMap.put("userId", "2001");
        payLoadMap.put("userName", "admin");
        // 设置过期时间
        Date expirDate = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        String token = Jwts.builder()
                .claims(payLoadMap)
                .expiration(expirDate)
                .issuedAt(new Date())
                .signWith(privateKey, Jwts.SIG.PS512)
                .compact();
        KeyPairVO keyPairVO = new KeyPairVO();
        keyPairVO.setPublicKey(publicKeyStr);
        keyPairVO.setPrivateKey(privateKeyStr);
        keyPairVO.setToken(token);
        return keyPairVO;
    }


    /**
     * 通过私钥获取token
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    public static String getTokenByPrivateKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
        String privateKeyStr = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCdrPTee8ghBorY1ifMl/J9nNNIU6mObaguf/CZx4QK38hhb0YZLR/yd/3j5bdBp0zDDWLSUTG1idQanDZ5K75OISb7ApSiOqgrruw+klIzUohpnRPlTljfdHesGmyCVpEhHwevlhQC+Yaew/3960NAWU6sHViXkYE7zC+HwWVKQJ/nnG3cTXd87S5CT10BaVs3G3n4ahQCs4z7MWTiXMAtS0i25Cq2Tf3MC3meEK4amdVJB0TD6ESiU9HLo1uBGuIGxunCvaP3s+LTFmIy9+givp4Sbo1h3F69WISW53lJLEB9L+P7TZAL9sQkfOiggZNs3Kz4xUtta02o6kMGbaxDAgMBAAECggEAUBtfDOm2c5DvWdrzvW41NLxIW6alrkbn+zfk9Tv4Sc4H7/iolIHoiTeNNguvXxuwVCio3FGD/8dWi25x/n3K4cbWFxDoksNaTVdBj0inmouD4qR7RzTW0jBJ3JZQKqfwc/Nf5EVLRXegfWj10duE/1xgK/F84QR7s/W48C/BVkdSQs6E1Mo3UNjZQkeR367k5JgvQjXFC20DgYrFWnIQumLIFYal26+AxFDVqlfmoZo2lUYOgCLaabX1lNMRMMyo21tgNrJcpHOJfe5FVkRUFvW2Zi0JKLnieoPqUbI9j+1h8QjxzVRrqGutyTc7JrPH6tqd3MQtooKNeL9tdieXgQKBgQDYQk8tlN1wNCcaWrd90ZQQS2R0tn7iGUAntTVnkPykdEYzaWRrinsKLc5cwl/ri0t2BlECuZZ1c9WZwLVXfCHlxpVpP5vp9bDozY+Z5prygpXOe0OC7MspI21lqin7w6icUjoHPz540qV68BZV6tqaJzOjhcsbFqnT4Og8dCr0NQKBgQC6pqYiXDwlF7A51ONfcEng2kTUlea15psD+jf4HGu1hbHH+9MwNOLZI9LfI+utkt3+cxVx2LulgUf5OIC6y0s1wu3A1agoy2PuM1o5kBJUwS0DiR4hDFsOkh6BS7yDCmmMEYj4Pgp4TyiE9CWWDATYzlBGKcQaoub/C7EIQCs9lwKBgFsglfy/HhCJ6XBRicCa76luG4aS4CSmP0J8OWTK06r41BwV7Rrj37UKWEr+HS1EJSg2wSxEyAH2Lav8aG3VAPOyGoOfKjQMM9/lvv07D0/hdv7rMieZYIKVSyPr8IUGjaZRf+JN5CVFnjWPtdm+fR84JapiVpOzmRyPSU0wJmmBAoGALtJPKp9olwVyN4+n2fEZF0aprYpM7aSDjmPeVmcKveZjyn7pY1Zg8YeDBmbEYC5Pcdz8rCpqKAJeQ65g3HrSyxGzAoSWQmWDE+Xd5EK31nr/B7wFytSGowkUjeqpx1V9VJ2xdlRZ3AQ/bdqw8wrgzGI00OT5RJVIzQHpzuAJ+NECgYB9Z5h7wyNh+g+D5TD7uL1FO688HabPXnfvqIa3XwtRGnLrrotnqwy0K9Wq9fdTChHWhP+jIgpMxByYq433jZXHsO/Rry43Mj6cAAlkZNAQp8x2jjH8G9+IZq0wh1L5WBbYdjiJlKKNLC1XfiAN/8qdfEWXIQUGsr80vL33WsJQDg==";
        // 将字符串Base64解码
        byte[] decodeKey = java.util.Base64.getDecoder().decode(privateKeyStr);
        // 创建x509证书封装类
        PKCS8EncodedKeySpec x509= new PKCS8EncodedKeySpec(decodeKey);
        // 指定RSA
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        // 生成私钥
        PrivateKey privateKey = keyFactory.generatePrivate(x509);
        Map<String, String> payLoadMap = new HashMap<>();
        payLoadMap.put("userId", "1001");
        payLoadMap.put("userName", "admin");
        // 设置过期时间
        Date expirDate = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        String token = Jwts.builder()
                .claims(payLoadMap)
                .expiration(expirDate)
                .issuedAt(new Date())
                .signWith(privateKey, Jwts.SIG.PS512)
                .compact();
        return token;
    }
}
package com.nancal.vo;

public class KeyPairVO {
    private String publicKey;
    private String privateKey;
    private String token;

    public String getPublicKey() {
        return publicKey;
    }
    public void setPublicKey(String publicKey) {
        this.publicKey = publicKey;
    }
    public String getPrivateKey() {
        return privateKey;
    }
    public void setPrivateKey(String privateKey) {
        this.privateKey = privateKey;
    }
    public String getToken() {
        return token;
    }
    public void setToken(String token) {
        this.token = token;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青春1314

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值