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.classification.InterfaceAudience;
29 import org.apache.hadoop.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 byte[] getIv() {
65 return iv;
66 }
67
68 @Override
69 public void setIv(byte[] iv) {
70 if (iv != null) {
71 Preconditions.checkArgument(iv.length == AES.IV_LENGTH, "Invalid IV length");
72 }
73 this.iv = iv;
74 }
75
76 @Override
77 public OutputStream createEncryptionStream(OutputStream out) {
78 if (!initialized) {
79 init();
80 }
81 return new javax.crypto.CipherOutputStream(out, cipher);
82 }
83
84 @Override
85 public void reset() {
86 init();
87 }
88
89 protected void init() {
90 try {
91 if (iv == null) {
92 iv = new byte[getIvLength()];
93 rng.nextBytes(iv);
94 }
95 cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
96 } catch (InvalidKeyException e) {
97 throw new RuntimeException(e);
98 } catch (InvalidAlgorithmParameterException e) {
99 throw new RuntimeException(e);
100 }
101 initialized = true;
102 }
103
104 }