jwt 加密和解密demo
JSON Web Token(JWT)是一個非常輕巧的規范。這個規范允許我們使用 JWT 在用戶和服務器之間傳遞安全可靠的信息。
導入jar
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.10.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.10.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.10.5</version>
<scope>runtime</scope>
</dependency>
JWTTest.java
package com.example.demo.jwt; import io.jsonwebtoken.*; import io.jsonwebtoken.security.Keys; import java.security.Key; import java.util.Date; import java.util.UUID; /** * JSON Web Token(JWT)是一個非常輕巧的規范。這個規范允許我們使用 JWT 在用戶和服務器之間傳遞安全可靠的信息。 * https://jwt.io/ * https://www.cnblogs.com/moonlightL/p/10020732.html */ public class JWTTest { public static void main(String[] args) { Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256); System.out.println("=============創建 JWT==========="); Date now = new Date(); JwtBuilder builder= Jwts.builder() .setId(UUID.randomUUID().toString()) // 載荷-標准中注冊的聲明 .setSubject("admin") // 載荷-標准中注冊的聲明 .setIssuedAt(now) // 載荷-標准中注冊的聲明,表示簽發時間 .claim("id", "123456") // 載荷-公共的聲明 .claim("name", "MoonlightL") // 載荷-公共的聲明 .claim("sex", "male") // 載荷-公共的聲明 .signWith(key); // 簽證 String jwt = builder.compact(); System.out.println("生成的 jwt :" +jwt); System.out.println("=============解析 JWT==========="); try { Jws<Claims> result = Jwts.parser().setSigningKey(key).parseClaimsJws(jwt); // 以下步驟隨實際情況而定,只要上一行代碼執行不拋異常就證明 jwt 是有效的、合法的 Claims body = result.getBody(); System.out.println("載荷-標准中注冊的聲明 id:" + body.getId()); System.out.println("載荷-標准中注冊的聲明 subject:" + body.getSubject()); System.out.println("載荷-標准中注冊的聲明 issueAt:" + body.getIssuedAt()); System.out.println("載荷-公共的聲明的 id:" + result.getBody().get("id")); System.out.println("載荷-公共的聲明的 name:" + result.getBody().get("name")); System.out.println("載荷-公共的聲明的 sex:" + result.getBody().get("sex")); } catch (JwtException ex) { // jwt 不合法或過期都會拋異常 ex.printStackTrace(); } } }
JWTTest2.java
package com.example.demo.jwt; import io.jsonwebtoken.*; import io.jsonwebtoken.security.Keys; import javax.crypto.spec.SecretKeySpec; import javax.xml.bind.DatatypeConverter; import java.security.Key; import java.util.Date; import java.util.UUID; /** * 報錯信息解決: * io.jsonwebtoken.security.WeakKeyException: The signing key's size is 96 bits which is not secure enough for the HS256 algorithm. The JWT JWA Specification (RFC 7518, Section 3.2) states that keys used with HS256 MUST have a size >= 256 bits (the key size must be greater than or equal to the hash output size). Consider using the io.jsonwebtoken.security.Keys class's 'secretKeyFor(SignatureAlgorithm.HS256)' method to create a key guaranteed to be secure enough for HS256. See https://tools.ietf.org/html/rfc7518#section-3.2 for more information. * 將JWS_SECRET key的長度加長。 */ public class JWTTest2 { private static final String JWS_SECRET = "fsfsfsfs1211212fdsfsfsdfsfsfsfsfsfaaaaeweweewsssssssssssssss"; private static final String JWS_BODY_KEY = "jwtTxt"; public static void main(String[] args) { String jwt = ""; try { System.out.println("=============創建 JWT==========="); String json = "你好中國2022"; //可以考慮存儲為json字符串 SignatureAlgorithm sa = SignatureAlgorithm.HS256; byte[] ksBytes = DatatypeConverter.parseBase64Binary(JWS_SECRET); Key signKey = new SecretKeySpec(ksBytes, sa.getJcaName()); JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT") .claim(JWS_BODY_KEY, json) .signWith(sa, signKey); jwt = builder.compact(); System.out.println("生成的 jwt :" +jwt); } catch (Exception e) { e.printStackTrace(); } System.out.println("=============解析 JWT==========="); try { Jws<Claims> jws = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(JWS_SECRET)) .parseClaimsJws(jwt.trim()); Claims body = jws.getBody(); Object jbk = body.get(JWS_BODY_KEY); System.out.println("content=" + jbk.toString().trim()); } catch (Exception e) { e.printStackTrace(); } } }
運行效果圖及驗證:
訪問地址: https://jwt.io/#debugger