View Javadoc

1   /**
2    * 
3    */
4   package org.treetank.io.bytepipe;
5   
6   import static com.google.common.base.Objects.toStringHelper;
7   
8   import java.io.InputStream;
9   import java.io.OutputStream;
10  import java.security.InvalidKeyException;
11  import java.security.Key;
12  import java.security.NoSuchAlgorithmException;
13  
14  import javax.crypto.Cipher;
15  import javax.crypto.CipherInputStream;
16  import javax.crypto.CipherOutputStream;
17  import javax.crypto.NoSuchPaddingException;
18  
19  import org.treetank.exception.TTByteHandleException;
20  
21  import com.google.inject.Inject;
22  
23  /**
24   * Decorator for encrypting any content.
25   * 
26   * @author Sebastian Graf, University of Konstanz
27   * 
28   */
29  public class Encryptor implements IByteHandler {
30  
31      /** Kind of the algorithm. */
32      private static final String ALGORITHM = "AES";
33  
34      /** Key for de-/encryption. */
35      private final Key mKey;
36  
37      /**
38       * Constructor.
39       * 
40       * @param pKey
41       *            to be injected
42       */
43      @Inject
44      public Encryptor(final Key pKey) {
45          mKey = pKey;
46      }
47  
48      /**
49       * {@inheritDoc}
50       * 
51       * @throws TTByteHandleException
52       */
53      public OutputStream serialize(final OutputStream pToSerialize) throws TTByteHandleException {
54          try {
55              final Cipher cipher = Cipher.getInstance(ALGORITHM);
56              cipher.init(Cipher.ENCRYPT_MODE, mKey);
57              return new CipherOutputStream(pToSerialize, cipher);
58          } catch (final InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException exc) {
59              throw new TTByteHandleException(exc);
60          }
61      }
62  
63      /**
64       * {@inheritDoc}
65       */
66      public InputStream deserialize(InputStream pToDeserialize) throws TTByteHandleException {
67          try {
68              final Cipher cipher = Cipher.getInstance(ALGORITHM);
69              cipher.init(Cipher.DECRYPT_MODE, mKey);
70              return new CipherInputStream(pToDeserialize, cipher);
71          } catch (final InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException exc) {
72              throw new TTByteHandleException(exc);
73          }
74  
75      }
76  
77      /**
78       * {@inheritDoc}
79       */
80      @Override
81      public Encryptor clone() {
82          return new Encryptor(mKey);
83      }
84  
85      /**
86       * {@inheritDoc}
87       */
88      @Override
89      public String toString() {
90          return toStringHelper(this).toString();
91      }
92  
93  }