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.InputStream;
21 import java.security.InvalidAlgorithmParameterException;
22 import java.security.InvalidKeyException;
23 import java.security.Key;
24
25 import javax.crypto.spec.IvParameterSpec;
26
27 import org.apache.hadoop.hbase.classification.InterfaceAudience;
28 import org.apache.hadoop.hbase.classification.InterfaceStability;
29 import org.apache.hadoop.hbase.io.crypto.Decryptor;
30
31 import com.google.common.base.Preconditions;
32
33 @InterfaceAudience.Private
34 @InterfaceStability.Evolving
35 public class AESDecryptor implements Decryptor {
36
37 private javax.crypto.Cipher cipher;
38 private Key key;
39 private byte[] iv;
40 private boolean initialized = false;
41
42 public AESDecryptor(javax.crypto.Cipher cipher) {
43 this.cipher = cipher;
44 }
45
46 javax.crypto.Cipher getCipher() {
47 return cipher;
48 }
49
50 @Override
51 public void setKey(Key key) {
52 Preconditions.checkNotNull(key, "Key cannot be null");
53 this.key = key;
54 }
55
56 @Override
57 public int getIvLength() {
58 return AES.IV_LENGTH;
59 }
60
61 @Override
62 public int getBlockSize() {
63 return AES.BLOCK_SIZE;
64 }
65
66 @Override
67 public void setIv(byte[] iv) {
68 Preconditions.checkNotNull(iv, "IV cannot be null");
69 Preconditions.checkArgument(iv.length == AES.IV_LENGTH, "Invalid IV length");
70 this.iv = iv;
71 }
72
73 @Override
74 public InputStream createDecryptionStream(InputStream in) {
75 if (!initialized) {
76 init();
77 }
78 return new javax.crypto.CipherInputStream(in, cipher);
79 }
80
81 @Override
82 public void reset() {
83 init();
84 }
85
86 protected void init() {
87 try {
88 if (iv == null) {
89 throw new NullPointerException("IV is null");
90 }
91 cipher.init(javax.crypto.Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
92 } catch (InvalidKeyException e) {
93 throw new RuntimeException(e);
94 } catch (InvalidAlgorithmParameterException e) {
95 throw new RuntimeException(e);
96 }
97 initialized = true;
98 }
99
100 }