1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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 }