云倾万里

无人问津的港口,总是开满鲜花

0%

JWT的加密与解密

JWT的简单使用

什么是JWT

JSON Web Token,通过JSON对象为载体,在不同的服务终端之间安全的传输信息

JWT有什么用?

JWT最常见的场景就是授权认证,一旦用户登录,后续每个请求都将包含JWT,系统在每次处理用户请求的之前,都要先进行JWT安全校验,通过之后在进行处理

JWT的组成

JWT由三部分组成,用.进行拼接

分别是:

  • Header
1
2
3
4
{
'typ': 'JWT',
'alg': 'HS256'
}
  • Payload
1
2
3
4
5
{
"sub": '1234567890',
"name": 'jhonny',
"admin": true
}
  • Signature
1
2
3
var encodedString = base64UrlEncode(header) + '.'+ base64UrlEncode(payload);

var signatrue = HMACSHA256(encodeedString,'secret');

signature是对header和payload分别进行base64加密,用.进行拼接,再使用HMACSHA256对前面的结果加密,这里的HMACSHA256是前面Header提前定义好的。

最后再将Header,Payload,Signature三部分用.拼接起来。

pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<dependencies>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>

jwt加密

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private long time = 1000*60*60*24; //有效时间
private String signature = "admin"; //唯一密钥,解密时需要声明

@org.junit.Test
public void jwt(){
JwtBuilder jwtBuilder = Jwts.builder();
String jwtToken = jwtBuilder
//header
.setHeaderParam("typ","JWT")
.setHeaderParam("alg","HS256")
//payload
.claim("username","tom")
.claim("role","admin")
.setSubject("admin-test")
.setExpiration(new Date(System.currentTimeMillis() + time))
.setId(UUID.randomUUID().toString())
//signature
.signWith(SignatureAlgorithm.HS256,signature)
.compact();
System.out.println(jwtToken);
}

jwt解密

1
2
3
4
5
6
7
8
9
10
11
12
@org.junit.Test
public void parse(){
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRvbSIsInJvbGUiOiJhZG1pbiIsInN1YiI6ImFkbWluLXRlc3QiLCJleHAiOjE2MzcyMTQzNjUsImp0aSI6ImVhNDVjM2RmLWNmNDMtNDA3ZC05YzM0LTFmMTc3NWE1ZmU5NyJ9.EVyXXebAwHVy33dfrQVUrwR5WnAX-3LhdMvJsFNuVWo"; //上面加密代码生成的
JwtParser jwtParser = Jwts.parser();
Jws<Claims> claimsJws = jwtParser.setSigningKey(signature).parseClaimsJws(token);
Claims claims = claimsJws.getBody();
System.out.println(claims.get("username"));
System.out.println(claims.get("role"));
System.out.println(claims.getId());
System.out.println(claims.getSubject());
System.out.println(claims.getExpiration());
}

Welcome to my other publishing channels