KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > core > security > AbstractStringEncryption


1 /* ====================================================================
2  * The Jcorporate Apache Style Software License, Version 1.2 05-07-2002
3  *
4  * Copyright (c) 1995-2002 Jcorporate Ltd. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by Jcorporate Ltd.
21  * (http://www.jcorporate.com/)."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. "Jcorporate" and product names such as "Expresso" must
26  * not be used to endorse or promote products derived from this
27  * software without prior written permission. For written permission,
28  * please contact info@jcorporate.com.
29  *
30  * 5. Products derived from this software may not be called "Expresso",
31  * or other Jcorporate product names; nor may "Expresso" or other
32  * Jcorporate product names appear in their name, without prior
33  * written permission of Jcorporate Ltd.
34  *
35  * 6. No product derived from this software may compete in the same
36  * market space, i.e. framework, without prior written permission
37  * of Jcorporate Ltd. For written permission, please contact
38  * partners@jcorporate.com.
39  *
40  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
41  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
42  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
43  * DISCLAIMED. IN NO EVENT SHALL JCORPORATE LTD OR ITS CONTRIBUTORS
44  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
45  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
46  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
47  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
48  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
49  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
50  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This software consists of voluntary contributions made by many
55  * individuals on behalf of the Jcorporate Ltd. Contributions back
56  * to the project(s) are encouraged when you make modifications.
57  * Please send them to support@jcorporate.com. For more information
58  * on Jcorporate Ltd. and its products, please see
59  * <http://www.jcorporate.com/>.
60  *
61  * Portions of this software are based upon other open source
62  * products and are subject to their respective licenses.
63  */

64
65 package com.jcorporate.expresso.core.security;
66
67 import com.jcorporate.expresso.core.misc.StringUtil;
68 import com.jcorporate.expresso.kernel.exception.ChainedException;
69 import org.apache.log4j.Logger;
70
71
72 /**
73  * This class represents a StringEncryption Interface
74  *
75  * @author Michael Rimov
76  */

77 abstract public class AbstractStringEncryption {
78     private static final String JavaDoc thisClass = "com.jcorporate.expresso.core.security.AbstracStringEncryption";
79     private static final String JavaDoc defaultPW = "Expresso Rocks";
80     private byte[] passKey = null;
81     boolean initialized = false;
82     static Logger logCat = Logger.getLogger(AbstractStringEncryption.class);
83
84     /**
85      * Instance to the parent
86      */

87     private CryptoManager cryptoManager;
88
89     /**
90      * Default Constructor
91      */

92     public AbstractStringEncryption() {
93         initialized = true;
94     } /* AbstractStringEncryption() */
95
96     public synchronized void init() throws ChainedException {
97         preparePassKey();
98     }
99
100     /**
101      * Retrieve the pass key prepped by the base class.
102      *
103      * @return byte[]
104      */

105     protected byte[] getPreparedPassKey() {
106         return passKey;
107     }
108
109     /**
110      * Implemented by lower levels to destroy the cryptographic managers.
111      */

112     public synchronized void destroy() {
113     }
114
115     /**
116      * Same as decryptString, but only deals in byte arrays. This method must be
117      * implemented by descendants of this class.
118      *
119      * @param inputData A byte aray of data to decrypt
120      * @return A byte array of decrypted data
121      * @throws ChainedException If there's an error decrypting the data
122      */

123     abstract public byte[] decrypt(byte[] inputData)
124             throws ChainedException;
125
126     /* decrypt(byte) */
127     /**
128      * Decode a string. Derived classes determine what strength/type of
129      * encoding is done.
130      *
131      * @param inputData A greater than zero length byte array. that was encoded
132      * with the encryptString() routine.
133      * @return the decrypted data in a String format.
134      */

135     public String JavaDoc decryptString(byte[] inputData)
136             throws IllegalStateException JavaDoc {
137         if (initialized == false) {
138             throw new IllegalStateException JavaDoc("StringEncryptionClass is not initialized!");
139         }
140         try {
141             if (inputData == null) {
142                 throw new IllegalArgumentException JavaDoc("inputData should not be null");
143             }
144             if (inputData.length == 0) {
145                 throw new IllegalArgumentException JavaDoc("inputData should be of length > 0");
146             }
147
148             return new String JavaDoc(decrypt(inputData));
149         } catch (Exception JavaDoc e) {
150
151             //If we have a problem with the data, the exception should be logged
152
logCat.error(thisClass + ".decryptString(byte)", e);
153
154             return "";
155         }
156     } /* decryptString(Byte[]) */
157
158
159     /**
160      * Same as encryptString, but only deals in byte arrays. This must be implemented
161      * by the descendants of this class.
162      *
163      * @param inputData A byte array to encrypt
164      * @return An encrypted byte array.
165      */

166     abstract public byte[] encrypt(byte[] inputData)
167             throws ChainedException;
168
169     /* encrypt(byte) */
170     /**
171      * Encode a string. Derived classes determine what strength/type of
172      * encoding is done.
173      *
174      * @param inputData a non-null string.
175      * @return a byte array that is the inputData encoded.
176      */

177     public byte[] encryptString(String JavaDoc inputData)
178             throws IllegalStateException JavaDoc,
179             IllegalArgumentException JavaDoc, ChainedException {
180
181         if (initialized == false) {
182             final String JavaDoc myName = thisClass + ".encryptString";
183             throw new IllegalStateException JavaDoc(myName +
184                     ":StringEncryptionClass is not initialized!");
185         }
186         if (inputData == null || inputData.length() == 0) {
187             return "".getBytes();
188         }
189
190         return encrypt(inputData.getBytes());
191     } /* encryptString(String) */
192
193
194     /**
195      * Basic implementation puts a hash of the config manager's key into
196      * the passKey variable.
197      */

198     public void preparePassKey()
199             throws ChainedException {
200         String JavaDoc pw = StringUtil.notNull(this.getCryptoManager().getCryptoKey());
201
202 // pw = StringUtil.notNull(ConfigManager.getConfig().getCryptoKey());
203

204         //Check if this property is set. If not, then set it to the default
205
//static key above.
206
if (pw.length() == 0) {
207             pw = defaultPW;
208             logCat.warn("Didn't find cryptoKey in config file, using default key.");
209         }
210
211         StringHash sha = new StringHash();
212
213         //Allocate a 256-bit key
214
passKey = new byte[256 / 8];
215
216         byte[] hash = sha.produceHash(pw.getBytes());
217
218         //
219
//The following operation truncates the 160-bit return of the SHA
220
//algorithm down to 128 bits.
221
//
222
for (int i = 0; i < hash.length; i++) {
223             passKey[i] = hash[i];
224         }
225         //
226
//Fill out the rest. Note at best we have only a 160 bit key.
227
//For a lousy salt, I simply repeat the passKey again until we've
228
//filled all the bits.
229
//
230
for (int i = hash.length; i < passKey.length; i++) {
231             passKey[i] = hash[i - hash.length];
232         }
233     }
234
235     public void setCryptoManager(CryptoManager cryptoManager) {
236         this.cryptoManager = cryptoManager;
237     }
238
239     public CryptoManager getCryptoManager() {
240         return cryptoManager;
241     } /* preparePassKey() */
242
243
244 } /* AbstractStringEncryption */
245
Popular Tags