1 package cn.home1.oss.lib.common.crypto;
2
3 import io.jsonwebtoken.Jwts;
4
5 import lombok.Getter;
6
7 import org.joda.time.DateTime;
8
9 import java.util.Date;
10
11 import cn.home1.oss.lib.common.Defaults;
12
13
14
15
16 public class JwtEncryptor implements EncodeEncryptor {
17
18 @Getter
19 private final JwtKey key;
20
21 public JwtEncryptor(final KeyExpression keyExpression) {
22 this.key = new JwtKey(keyExpression);
23 }
24
25 @Override
26 public String encrypt(final String plainText) {
27 throw new UnsupportedOperationException("jwt without maxAge is not supported.");
28 }
29
30 @Override
31 public String encrypt(final String plainText, final Integer maxAge) {
32 return this.buildCompactJws(plainText, Defaults.now(), maxAge);
33 }
34
35 public String buildCompactJws(final String token, final DateTime now, final Integer maxAge) {
36 final Date expiration = now.plusSeconds(maxAge).toDate();
37 return token != null ? Jwts.builder()
38 .setSubject(token)
39 .signWith(this.key.getSignatureAlgorithm(), this.key.getSignatureKey())
40 .setExpiration(expiration)
41 .compact() : null;
42 }
43 }