美文网首页
java使用私钥生成JWT

java使用私钥生成JWT

作者: 阿拉斌 | 来源:发表于2019-07-31 18:19 被阅读0次

JWT是什么我就不多说,可以自行百度,然后现在要做的呢,就是使用私钥生成JWT,以及JWT的解密

首先,我们需要生成私钥和公钥

必须要有git哦,不然openssl命令不好用,我们直接可以再git的Bash上面敲下面的命令

第一步:生成私钥,这里我们指定私钥的长度为2048
openssl genrsa -out rsa_private_key.pem 2048

第二步:根据私钥生成对应的公钥:下面两个都可以

1: openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
2: openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key_2048.pub 

第三步:私钥转化成pkcs8格式,尖括号的意思是:将转化好的私钥写到rsa_private_key_pkcs8.pem文件里
openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt > rsa_private_key_pkcs8.pem

注意:第三步是必须的,我开始直接使用第一步生成的私钥,java老是给我报错,至于是什么错,可以自己去试试

注意2:生成的文件不能直接用,需要删除头和尾巴,也就是删除-----BEGIN PUBLIC KEY----------END PUBLIC KEY-----

我们把这里文件给放在这里:


image.png

好了,现在的问题出来了,我们改如何获取这些文件呢?

错误的方法1:

    public static String readResourceKey(String fileName) {
        String key = null;
        try {
            Resource resource = new ClassPathResource(fileName);
            File file =  resource.getFile();
            List<String> lines = FileUtils.readLines(file, String.valueOf(Charset.defaultCharset()));
            lines = lines.subList(1, lines.size() - 1);
            key = lines.stream().collect(Collectors.joining());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return key;
    }

因为在打包成jar后,就无法读取resources里面的文件了

正确的方法:

    /**
     * 读取资源文件
     *
     * @param fileName 文件的名称
     * @return
     */
    public static String readResourceKey(String fileName) {
        String key = null;
        try {
            InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
            assert inputStream != null;
            key = IOUtils.toString(inputStream, String.valueOf(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return key;
    }

注意:pom也需要改一下,要让maven忽略掉这些密钥文件

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <configuration>
      <encoding>UTF-8</encoding>
      <!-- 过滤后缀为pem、pfx的证书文件 -->
      <nonFilteredFileExtensions>
      <nonFilteredFileExtension>cer</nonFilteredFileExtension>
      <nonFilteredFileExtension>pem</nonFilteredFileExtension>
      <nonFilteredFileExtension>pfx</nonFilteredFileExtension>
      </nonFilteredFileExtensions>
    </configuration>
  </plugin>

然后是完整代码:

import com.alibaba.fastjson.JSON;
import com.theling.common.vo.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.io.IOUtils;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JwtToken class
 *
 * @author tangbin
 * @date 2018年7月7日12:28:13
 */
public class JwtUtils {

    private static final String SECRET = "h8t^$r1%qK8rvmbUm5453VR#H1sMWLTj!#neA39";

    /**
     * 读取资源文件
     *
     * @param fileName 文件的名称
     * @return
     */
    public static String readResourceKey(String fileName) {
        String key = null;
        try {
            InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
            assert inputStream != null;
            key = IOUtils.toString(inputStream, String.valueOf(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return key;
    }

    /**
     * 构建token
     * @param user 用户对象
     * @param ttlMillis 过期的时间-毫秒
     * @return
     * @throws Exception
     */
    public static String buildJwtRS256(LoginUser user, long ttlMillis) throws Exception {

        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.RS256;
        // 读取私钥
        String key = readResourceKey("static/rsa_private_key_pkcs8.pem");

        // 生成签名密钥
        byte[] keyBytes = (new BASE64Decoder()).decodeBuffer(key);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

        // 生成JWT的时间
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        //创建payload的私有声明(根据特定的业务需要添加,如果要拿这个做验证,一般是需要和jwt的接收方提前沟通好验证方式的)
        Map<String,Object> claims = new HashMap<String,Object>();
        claims.put("userid", user.getUserid());
        claims.put("username", user.getUsername());
        claims.put("usertype",user.getUsertype());

        // 生成jwt文件
        JwtBuilder builder = Jwts.builder()
                // 这里其实就是new一个JwtBuilder,设置jwt的body
                // 如果有私有声明,一定要先设置这个自己创建的私有的声明,这个是给builder的claim赋值,一旦写在标准的声明赋值之后,就是覆盖了那些标准的声明的
                .setClaims(claims)
                .setHeaderParam("typ", "JWT")
                .setIssuedAt(now)
                .setSubject(JSON.toJSONString(user))
                .signWith(signatureAlgorithm, privateKey);

        // 如果配置了过期时间
        if (ttlMillis >= 0) {
            // 当前时间加上过期的秒数
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            // 设置过期时间
            builder.setExpiration(exp);
        }
        return builder.compact();
    }

    /**
     * 解密Jwt内容
     *
     * @param jwt
     * @return
     */
    public static String parseJwtRS256(String jwt) {
        Claims claims = null;
        try {
            // 读取公钥
            String key = readResourceKey("static/rsa_public_key.pem");
            // 生成签名公钥
            byte[] keyBytes = (new BASE64Decoder()).decodeBuffer(key);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey publicKey = keyFactory.generatePublic(keySpec);
            claims = Jwts.parser()
                    .setSigningKey(publicKey)
                    .parseClaimsJws(jwt).getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return claims.get("uid", String.class);
    }
}

然后就可以愉快的玩耍了

相关文章

网友评论

      本文标题:java使用私钥生成JWT

      本文链接:https://www.haomeiwen.com/subject/mqatdctx.html