1 package cn.home1.oss.lib.common.crypto;
2
3 import io.jsonwebtoken.Claims;
4 import io.jsonwebtoken.Clock;
5 import io.jsonwebtoken.Jws;
6 import io.jsonwebtoken.Jwts;
7 import io.jsonwebtoken.impl.FixedClock;
8
9 import lombok.Getter;
10
11 import org.joda.time.DateTime;
12
13 import cn.home1.oss.lib.common.Defaults;
14
15
16
17
18 public class JwtDecryptor implements EncodeDecryptor {
19
20 @Getter
21 private final JwtKey key;
22
23 public JwtDecryptor(final KeyExpression keyExpression) {
24 this.key = new JwtKey(keyExpression);
25 }
26
27
28
29
30
31
32 @Override
33 public String decrypt(final String encryptedAndEncoded) {
34 final Jws<Claims> jws = encryptedAndEncoded != null ?
35 this.parseCompactJws(encryptedAndEncoded, Defaults.now()) : null;
36 return jws != null ? jws.getBody().getSubject() : null;
37 }
38
39 public Jws<Claims> parseCompactJws(final String compactJws, final DateTime dateTime) {
40 final Clock clock = new FixedClock(dateTime.toDate());
41 return compactJws != null ?
42 Jwts.parser().setClock(clock).setSigningKey(this.key.getSignatureKey()).parseClaimsJws(compactJws) : null;
43 }
44 }