JWT的使用

1.RAS工具类


import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * RAS工具类
 */
public class RSAUtil {

    /**
     * 读取公钥
     * @param filename
     * @return
     * @throws Exception
     */
    public static PublicKey getPublicKey(String filename) throws Exception {
        byte[] bytes = readFile(filename);
        return getPublicKey(bytes);
    }

    /**
     * 获取公钥
     * @param bytes
     * @return
     * @throws Exception
     */
    public static PublicKey getPublicKey(byte[] bytes) throws Exception {
        X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);
        KeyFactory factory = KeyFactory.getInstance("RSA");
        return factory.generatePublic(spec);
    }

    /**
     * 读取私钥
     * @param filename
     * @return
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(String filename) throws Exception {
        byte[] bytes = readFile(filename);
        return getPrivateKey(bytes);
    }

    /**
     * 获取私钥
     * @param bytes
     * @return
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(byte[] bytes) throws Exception {
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
        KeyFactory factory = KeyFactory.getInstance("RSA");
        return factory.generatePrivate(spec);
    }

    /**
     * 根据随机种子生产公钥和私钥并且保存到文件中
     * @param publicKeyFilePath    公钥保存路径
     * @param privateKeyFilePath   私钥保存路径
     * @param seed                 随机种子
     * @throws Exception
     */
    public static void generateKey(String publicKeyFilePath, String privateKeyFilePath, String seed) throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        SecureRandom secureRandom = new SecureRandom(seed.getBytes());
        keyPairGenerator.initialize(1024, secureRandom);
        KeyPair keyPair = keyPairGenerator.genKeyPair();
        // 获取公钥并写出
        byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
        writeFile(publicKeyFilePath, publicKeyBytes);
        // 获取私钥并写出
        byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
        writeFile(privateKeyFilePath, privateKeyBytes);
    }

    /**
     * 读取文件
     * @param fileName
     * @return
     * @throws Exception
     */
    private static byte[] readFile(String fileName) throws Exception {
        return Files.readAllBytes(new File(fileName).toPath());
    }

    /**
     * 写入文件
     * @param destPath
     * @param bytes
     * @throws IOException
     */
    private static void writeFile(String destPath, byte[] bytes) throws IOException {
        File dest = new File(destPath);
        if (!dest.exists()) {
            dest.createNewFile();
        }
        Files.write(dest.toPath(), bytes);
    }
}

2.JWT工具类

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

import java.security.PrivateKey;
import java.security.PublicKey;

public class JWTUtil {

    /**
     * 私钥生成Token
     * @param oriInfo
     * @param privateKey
     * @param expire      过期时间,单位秒
     * @return
     * @throws Exception
     */
    public static String generateToken(String oriInfo, PrivateKey privateKey, int expire)  {
        return Jwts.builder()
                .claim("info",oriInfo)
                .setExpiration(DateTime.now().plusSeconds(expire).toDate())
                .signWith(SignatureAlgorithm.RS256,privateKey)
                .compact();
    }

    /**
     * 从token中获取原始信息
     * @param token
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static String getInfoFromToken(String token, PublicKey publicKey)  {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        return body.get("info")+"";
    }
}

3.JWT测试类

package com.neu.eml.utils;

import java.security.PrivateKey;
import java.security.PublicKey;

public class JWTTest {
    //公钥
    private static final String publicKeyPath = "E:\\rsa\\rsa.pub";
    //私钥
    private static final String priKeyPath = "E:\\rsa\\rsa.pri";
    private PublicKey publicKey;
    private PrivateKey privateKey;

    public static void main(String[] args) {

    }
  public void testRsa() throws Exception {
        RSAUtil.generateKey(publicKeyPath,priKeyPath,"abc");
  }
  public void testJWT() throws Exception {
        this.publicKey = RSAUtil.getPublicKey(publicKeyPath);
        this.privateKey = RSAUtil.getPrivateKey(priKeyPath);
        //生成token
        String token = JWTUtil.generateToken("ZHANGSAN",privateKey,2);
        System.out.println(token);
        Thread.sleep(3000);
        String oriInfo = JWTUtil.getInfoFromToken(token,publicKey);
        System.out.println(oriInfo);
  }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值