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.classification.InterfaceAudience;
28 import org.apache.hadoop.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 void setIv(byte[] iv) {
63 Preconditions.checkNotNull(iv, "IV cannot be null");
64 Preconditions.checkArgument(iv.length == AES.IV_LENGTH, "Invalid IV length");
65 this.iv = iv;
66 }
67
68 @Override
69 public InputStream createDecryptionStream(InputStream in) {
70 if (!initialized) {
71 init();
72 }
73 return new javax.crypto.CipherInputStream(in, cipher);
74 }
75
76 @Override
77 public void reset() {
78 init();
79 }
80
81 protected void init() {
82 try {
83 if (iv == null) {
84 throw new NullPointerException("IV is null");
85 }
86 cipher.init(javax.crypto.Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
87 } catch (InvalidKeyException e) {
88 throw new RuntimeException(e);
89 } catch (InvalidAlgorithmParameterException e) {
90 throw new RuntimeException(e);
91 }
92 initialized = true;
93 }
94
95 }