1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.hadoop.hbase.io.crypto.aes;
19
20 import java.io.OutputStream;
21 import java.security.InvalidAlgorithmParameterException;
22 import java.security.InvalidKeyException;
23 import java.security.Key;
24 import java.security.SecureRandom;
25
26 import javax.crypto.spec.IvParameterSpec;
27
28 import org.apache.hadoop.hbase.classification.InterfaceAudience;
29 import org.apache.hadoop.hbase.classification.InterfaceStability;
30 import org.apache.hadoop.hbase.io.crypto.Encryptor;
31
32 import com.google.common.base.Preconditions;
33
34 @InterfaceAudience.Private
35 @InterfaceStability.Evolving
36 public class AESEncryptor implements Encryptor {
37
38 private javax.crypto.Cipher cipher;
39 private SecureRandom rng;
40 private Key key;
41 private byte[] iv;
42 private boolean initialized = false;
43
44 public AESEncryptor(javax.crypto.Cipher cipher, SecureRandom rng) {
45 this.cipher = cipher;
46 this.rng = rng;
47 }
48
49 javax.crypto.Cipher getCipher() {
50 return cipher;
51 }
52
53 @Override
54 public void setKey(Key key) {
55 this.key = key;
56 }
57
58 @Override
59 public int getIvLength() {
60 return AES.IV_LENGTH;
61 }
62
63 @Override
64 public int getBlockSize() {
65 return AES.BLOCK_SIZE;
66 }
67
68 @Override
69 public byte[] getIv() {
70 return iv;
71 }
72
73 @Override
74 public void setIv(byte[] iv) {
75 if (iv != null) {
76 Preconditions.checkArgument(iv.length == AES.IV_LENGTH, "Invalid IV length");
77 }
78 this.iv = iv;
79 }
80
81 @Override
82 public OutputStream createEncryptionStream(OutputStream out) {
83 if (!initialized) {
84 init();
85 }
86 return new javax.crypto.CipherOutputStream(out, cipher);
87 }
88
89 @Override
90 public void reset() {
91 init();
92 }
93
94 protected void init() {
95 try {
96 if (iv == null) {
97 iv = new byte[getIvLength()];
98 rng.nextBytes(iv);
99 }
100 cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
101 } catch (InvalidKeyException e) {
102 throw new RuntimeException(e);
103 } catch (InvalidAlgorithmParameterException e) {
104 throw new RuntimeException(e);
105 }
106 initialized = true;
107 }
108
109 }