1 package cn.home1.oss.lib.common.crypto;
2
3 import static com.google.common.base.Preconditions.checkArgument;
4
5 import io.jsonwebtoken.SignatureAlgorithm;
6 import io.jsonwebtoken.impl.crypto.MacProvider;
7
8 import lombok.Getter;
9
10 import cn.home1.oss.lib.common.CodecUtils;
11
12
13
14
15 public class JwtKeyGenerator implements KeyGenerator {
16
17 @Getter
18 private final String spec;
19 @Getter
20 private KeyExpression key;
21
22 public JwtKeyGenerator(final String spec) {
23 this.spec = spec;
24 }
25
26 @Override
27 public KeyExpression generateKey() {
28 return JwtKeyGenerator.generateJwtKey(this.spec);
29 }
30
31 @Override
32 public KeyExpression getKey(final String spec) {
33 checkArgument(this.spec.equals(spec), "spec " + spec + " not supported.");
34 if (this.key == null) {
35 this.key = this.generateKey();
36 }
37 return this.key;
38 }
39
40
41
42
43
44
45
46 public static KeyExpression generateJwtKey(final String spec) {
47 final String signatureAlgorithmName = "" + spec;
48 final SignatureAlgorithm algorithm = SignatureAlgorithm.forName(signatureAlgorithmName);
49 return new KeyExpression(
50 spec,
51 CodecUtils.encodeBase64(MacProvider.generateKey(algorithm).getEncoded())
52 );
53 }
54 }