超简单JWT示例

27 阅读2分钟

| 使用auth0包完成JWT的非对称加密(RSA)

  1. 安装auth0
<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>4.2.1</version>
</dependency>
  1. 生成公私钥

// 初始化 Key 生成器,指定算法类型为 RSA
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");

// 密钥长度为 2048 位
keyPairGenerator.initialize(1024);

// 生成密钥对
KeyPair keyPair = keyPairGenerator.generateKeyPair();

// 获取公钥
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();

// 获取私钥
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();

System.out.println("公钥:" + Base64.getEncoder().encodeToString(rsaPublicKey.getEncoded()));

System.out.println("私钥:" + Base64.getEncoder().encodeToString(rsaPrivateKey.getEncoded()));

  1. 加密
//将string转为字节数组;PUBLIC_KEY与PRIVATE_KEY为上文生成的公私钥(String类型)
byte[] publicKeyBytes = Base64.getDecoder().decode(PUBLIC_KEY);
byte[] privateKeyBytes = Base64.getDecoder().decode(PRIVATE_KEY);


//转换字节数组
X509EncodedKeySpec encodedPublicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
PKCS8EncodedKeySpec encodedPrivateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);


// 使用公钥的字节数组创建 X509EncodedKeySpec
X509EncodedKeySpec encodedPublicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
// 使用私钥的字节数组创建 PKCS8EncodedKeySpec
PKCS8EncodedKeySpec encodedPrivateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);

// 创建 KeyFactory 实例,指定算法为 RSA
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
// 使用公钥的规范生成 PublicKey 对象
PublicKey publicKey = keyFactory.generatePublic(encodedPublicKeySpec);
// 使用私钥的规范生成 PrivateKey 对象
PrivateKey privateKey = keyFactory.generatePrivate(encodedPrivateKeySpec);

// 将 PublicKey 对象转换为 RSAPublicKey
RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
// 将 PrivateKey 对象转换为 RSAPrivateKey
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;

//System.out.println("publicKeyBytes = " + Arrays.toString(publicKeyBytes));
//System.out.println("rsaPrivateKey = " + rsaPrivateKey);


// 使用 RSAPublicKey 和 RSAPrivateKey 创建 Algorithm 对象
//加密需要传入公私秘钥,顺序不能反,先公有后私有
Algorithm algorithm = Algorithm.RSA512(rsaPublicKey, rsaPrivateKey);

// 使用 Algorithm 对象生成 JWT
String token = JWT.create()
        .withClaim("uid", 12321132131L)  // 自定义内容
        .withExpiresAt(new Date())//表示令牌的过期时间
        .sign(algorithm);

System.out.println("token = " + token);
System.out.println("======================加密完成===================");

  1. 解密
//与上文的不一样,解密只用传入公钥
Algorithm algorithm1 = Algorithm.RSA512(rsaPublicKey);

JWTVerifier jwtVerifier = JWT.require(algorithm1).build();

DecodedJWT verify = jwtVerifier.verify(token);

System.out.println(verify.getClaims());//获取载荷
System.out.println(verify.getClaim("uid"));//获取指定载荷
System.out.println("======================解密完成===================");


image.png

注意事项:

  • Algorithm应该与对应的秘钥方式对应.
  • RSA公钥只支持RSAPublicKeySpecX509EncodedKeySpec(代码第7行)
  • RSA私钥只支持PKCS8EncodedKeySpec