View Javadoc

1   /*
2   Copyright 2011-2014 AGH-UST, http://www.agh.edu.pl
3   Faculty of Computer Science, Electronics and Telecommunications
4   Department of Computer Science 
5   
6   See the NOTICE file distributed with this work for additional
7   information regarding copyright ownership
8   
9   Licensed under the Apache License, Version 2.0 (the "License");
10  you may not use this file except in compliance with the License.
11  You may obtain a copy of the License at
12  
13    http://www.apache.org/licenses/LICENSE-2.0
14  
15  Unless required by applicable law or agreed to in writing, software
16  distributed under the License is distributed on an "AS IS" BASIS,
17  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  See the License for the specific language governing permissions and
19  limitations under the License.
20  */
21  package org.universAAL.ri.gateway.communicator.service.impl;
22  
23  import org.bouncycastle.crypto.*;
24  import org.bouncycastle.crypto.engines.*;
25  import org.bouncycastle.crypto.modes.*;
26  import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
27  import org.bouncycastle.crypto.params.*;
28  
29  public enum SecurityUtils {
30  
31  	Instance;
32  	
33  	private static PaddedBufferedBlockCipher cipher;
34      private static KeyParameter key;
35  
36      public synchronized void initialize(String encryptionKey){
37      	if (null == cipher){
38      		cipher = new PaddedBufferedBlockCipher(
39                      new CBCBlockCipher(
40                      new BlowfishEngine() ) );
41      	}
42          key = new KeyParameter( encryptionKey.getBytes() );
43      }
44  	
45      
46      private static byte[] callCipher( byte[] data )
47      throws CryptoException {
48          int    size =
49                  cipher.getOutputSize( data.length );
50          byte[] result = new byte[ size ];
51          int    olen = cipher.processBytes( data, 0,
52                  data.length, result, 0 );
53          olen += cipher.doFinal( result, olen );
54          
55          if( olen < size ){
56              byte[] tmp = new byte[ olen ];
57              System.arraycopy(
58                      result, 0, tmp, 0, olen );
59              result = tmp;
60          }
61          
62          return result;
63      }
64      
65      public synchronized byte[] encrypt( byte[] data )
66      throws CryptoException {
67          if( data == null || data.length == 0 ){
68              return new byte[0];
69          }
70          
71          cipher.init( true, key );
72          return callCipher( data );
73      }
74      
75      public synchronized byte[] decrypt( byte[] data )
76      throws CryptoException {
77          if( data == null || data.length == 0 ){
78              return new byte[0];
79          }
80          
81          cipher.init( false, key );
82          return callCipher( data );
83      }
84      
85  }