View Javadoc
1   package cn.home1.oss.lib.common.crypto;
2   
3   import static com.google.common.base.Preconditions.checkArgument;
4   
5   import lombok.Getter;
6   
7   /**
8    * Created by zhanghaolun on 16/11/17.
9    */
10  public class AesKeyGenerator implements KeyGenerator {
11  
12    @Getter
13    private final String spec;
14    private KeyExpression key;
15  
16    public AesKeyGenerator(final String spec) {
17      this.spec = spec;
18    }
19  
20    @Override
21    public KeyExpression generateKey() {
22      this.key = AesKeyGenerator.generateAesKey(this.spec);
23      return this.key;
24    }
25  
26    @Override
27    public KeyExpression getKey(final String spec) {
28      checkArgument(this.spec.equals(spec), "spec " + spec + " not supported.");
29      if (this.key == null) {
30        this.generateKey();
31      }
32      return this.key;
33    }
34  
35    public static KeyExpression generateAesKey(final String spec) {
36      final int keySize = AesCbcKey.keySize(spec);
37      final String value;
38      if (keySize == 256) {
39        value = RandomString.RandomStrings.RANDOM_BASE62.generate(43) + "="; // 32bytes after decoded
40      } else {
41        throw new IllegalArgumentException("unsupported spec " + spec);
42      }
43      return new KeyExpression(spec, value);
44    }
45  }