KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > compiere > util > Secure


1 /******************************************************************************
2  * The contents of this file are subject to the Compiere License Version 1.1
3  * ("License"); You may not use this file except in compliance with the License
4  * You may obtain a copy of the License at http://www.compiere.org/license.html
5  * Software distributed under the License is distributed on an "AS IS" basis,
6  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
7  * the specific language governing rights and limitations under the License.
8  * The Original Code is Compiere ERP & CRM Business Solution
9  * The Initial Developer of the Original Code is Jorg Janke and ComPiere, Inc.
10  * Portions created by Jorg Janke are Copyright (C) 1999-2001 Jorg Janke, parts
11  * created by ComPiere are Copyright (C) ComPiere, Inc.; All Rights Reserved.
12  * Contributor(s): ______________________________________.
13  *****************************************************************************/

14 package org.compiere.util;
15
16 import java.security.AlgorithmParameters JavaDoc;
17 import java.security.MessageDigest JavaDoc;
18 import java.security.NoSuchAlgorithmException JavaDoc;
19
20 import javax.crypto.Cipher;
21 import javax.crypto.KeyGenerator;
22 import javax.crypto.SecretKey;
23
24 /**
25  * Security Services (Open Source - none).
26  *
27  * @author Jorg Janke
28  * @version $Id: Secure.java,v 1.10 2003/09/27 11:13:27 jjanke Exp $
29  */

30 public class Secure
31 {
32     /*************************************************************************/
33
34     private static Cipher s_cipher = null;
35     private static SecretKey s_key = null;
36
37     /** Clear Text Indiactor **/
38     public static final String JavaDoc CLEARTEXT = "xyz";
39
40     /**
41      * Initialize Cipher & Key
42      */

43     private static void initCipher()
44     {
45         try
46         {
47             s_cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
48             // Key
49
if (false)
50             {
51                 KeyGenerator keygen = KeyGenerator.getInstance("DES");
52                 s_key = keygen.generateKey();
53                 byte[] key = s_key.getEncoded();
54                 System.out.print("Key " + s_key.getAlgorithm() + "(" + key.length + ")= ");
55                 for (int i = 0; i < key.length; i++)
56                     System.out.print(key[i] + ",");
57                 System.out.println("");
58             }
59             else
60                 s_key = new javax.crypto.spec.SecretKeySpec(new byte[] {100,25,28,-122,-26,94,-3,-26}, "DES");
61         }
62         catch (Exception JavaDoc ex)
63         {
64             ex.printStackTrace();
65         }
66     } // initCipher
67

68     /**
69      * Encryption
70      * @param value clear value
71      * @return encrypted String
72      */

73     public static String JavaDoc encrypt (String JavaDoc value)
74     {
75         String JavaDoc clearText = value;
76         if (clearText == null)
77             clearText = "";
78         // Init
79
if (s_cipher == null)
80             initCipher();
81         // Encrypt
82
if (s_cipher != null)
83         {
84             try
85             {
86                 s_cipher.init(Cipher.ENCRYPT_MODE, s_key);
87                 byte[] encBytes = s_cipher.doFinal(clearText.getBytes());
88                 String JavaDoc encString = convertToHexString(encBytes);
89             // System.out.println("Secure.encrypt=" + encString);
90
return encString;
91             }
92             catch (Exception JavaDoc ex)
93             {
94                 ex.printStackTrace();
95             }
96         }
97         return CLEARTEXT + value;
98     } // encrypt
99

100     /**
101      * Decryption
102      * @param value encrypted value
103      * @return decrypted String
104      */

105     public static String JavaDoc decrypt (String JavaDoc value)
106     {
107         if (value == null)
108             return null;
109         if (value.length() == 0)
110             return value;
111         if (value.startsWith(CLEARTEXT))
112             return value.substring(3);
113         // Init
114
if (s_cipher == null)
115             initCipher();
116
117         // Encrypt
118
if (s_cipher != null && value != null && value.length() > 0)
119         {
120             try
121             {
122                 AlgorithmParameters JavaDoc ap = s_cipher.getParameters();
123                 s_cipher.init(Cipher.DECRYPT_MODE, s_key, ap);
124                 byte[] out = s_cipher.doFinal(convertHexString(value));
125             // System.out.println ("Secure.decrypt=" + value + " => " + new String(out));
126
return new String JavaDoc(out);
127             }
128             catch (Exception JavaDoc ex)
129             {
130                 System.err.println ("Secure.decrypt=" + value);
131                 ex.printStackTrace();
132             }
133         }
134         return value;
135     } // decrypt
136

137     /*************************************************************************/
138
139     /**
140      * Hash checksum number
141      * @param key key
142      * @return checksum number
143      */

144     public static int hash (String JavaDoc key)
145     {
146         long tableSize = 2147483647; // one less than max int
147
long hashValue = 0;
148
149         for (int i = 0; i < key.length(); i++)
150             hashValue = (37 * hashValue) + (key.charAt(i) -31);
151
152         hashValue %= tableSize;
153         if (hashValue < 0)
154             hashValue += tableSize;
155
156         int retValue = (int)hashValue;
157         return retValue;
158     } // hash
159

160     /*************************************************************************/
161
162     /**
163      * Convert Message to Digest.
164      * JavaScript version see - http://pajhome.org.uk/crypt/md5/index.html
165      *
166      * @param message message
167      * @return HexString of message (length = 32 characters)
168      */

169     public static String JavaDoc getDigest (String JavaDoc message)
170     {
171         MessageDigest JavaDoc md = null;
172         try
173         {
174             md = MessageDigest.getInstance("MD5");
175         // md = MessageDigest.getInstance("SHA-1");
176
}
177         catch (NoSuchAlgorithmException JavaDoc nsae)
178         {
179             nsae.printStackTrace();
180         }
181         // Reset MessageDigest object
182
md.reset();
183         // Convert String to array of bytes
184
byte[] input = message.getBytes();
185         // feed this array of bytes to the MessageDigest object
186
md.update(input);
187         // Get the resulting bytes after the encryption process
188
byte[] output = md.digest();
189         md.reset();
190         //
191
return convertToHexString(output);
192     } // getDigest
193

194     /**
195      * Checks, if value is a valid digest
196      * @param value digest string
197      * @return true if valid digest
198      */

199     public static boolean isDigest (String JavaDoc value)
200     {
201         if (value == null || value.length() != 32)
202             return false;
203         // needs to be a hex string, so try to convert it
204
return (convertHexString(value) != null);
205     } // isDigest
206

207     /*************************************************************************/
208
209     /**
210      * Convert Byte Array to Hex String
211      * @param bytes bytes
212      * @return HexString
213      */

214     static private String JavaDoc convertToHexString (byte[] bytes)
215     {
216         // see also Util.toHex
217
int size = bytes.length;
218         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(size*2);
219         for(int i=0; i<size; i++)
220         {
221             // convert byte to an int
222
int x = bytes[i];
223             // account for int being a signed type and byte being unsigned
224
if (x < 0)
225                 x += 256;
226             String JavaDoc tmp = Integer.toHexString(x);
227             // pad out "1" to "01" etc.
228
if (tmp.length() == 1)
229                 buffer.append("0");
230             buffer.append(tmp);
231         }
232         return buffer.toString();
233     } // convertToHexString
234

235
236     /**
237      * Convert Hex String to Byte Array
238      * @param hexString hex string
239      * @return byte array
240      */

241     static private byte[] convertHexString (String JavaDoc hexString)
242     {
243         int size = hexString.length()/2;
244         byte[] retValue = new byte[size];
245         String JavaDoc inString = hexString.toLowerCase();
246
247         try
248         {
249             for (int i = 0; i < size; i++)
250             {
251                 int index = i*2;
252                 int ii = Integer.parseInt(inString.substring(index, index+2), 16);
253                 retValue[i] = (byte)ii;
254             }
255             return retValue;
256         }
257         catch (Exception JavaDoc e)
258         {
259             System.err.println("Secure.convertHexString error - " + e.getMessage());
260         }
261         return null;
262     } // convertToHexString
263

264     /*************************************************************************/
265
266     /**
267      * Test
268      * @param args ignored
269      */

270     public static void main (String JavaDoc[] args)
271     {
272         String JavaDoc[] testString = new String JavaDoc[]
273             {"This is a test!", "", "This is a verly long test string 1624$%"};
274         String JavaDoc[] digestResult = new String JavaDoc[]
275             {"702edca0b2181c15d457eacac39de39b", "d41d8cd98f00b204e9800998ecf8427e", "934e7c5c6f5508ff50bc425770a10f45"};
276
277         for (int i = 0; i < testString.length; i++)
278         {
279             String JavaDoc digestString = getDigest(testString[i]);
280             if (digestResult[i].equals(digestString))
281                 System.out.println("OK - digest");
282             else
283                 System.err.println("Digest=" + digestString + " <> " + digestResult[i]);
284         }
285
286         System.out.println("IsDigest true=" + isDigest(digestResult[0]));
287         System.out.println("IsDigest false=" + isDigest("702edca0b2181c15d457eacac39DE39J"));
288         System.out.println("IsDigest false=" + isDigest("702e"));
289
290     // -----------------------------------------------------------------------
291

292     // System.out.println(convertToHexString(new byte[]{Byte.MIN_VALUE, -1, 1, Byte.MAX_VALUE} ));
293
//
294
String JavaDoc in = "4115da655707807F00FF";
295         byte[] bb = convertHexString(in);
296         String JavaDoc out = convertToHexString(bb);
297         if (in.equalsIgnoreCase(out))
298             System.out.println("OK - conversion");
299         else
300             System.err.println("Conversion Error " + in + " <> " + out );
301
302     // -----------------------------------------------------------------------
303

304         String JavaDoc test = "This is a test!!";
305         String JavaDoc result = "28bd14203bcefba1c5eaef976e44f1746dc2facaa9e0623c";
306         //
307
String JavaDoc test_1 = decrypt(result);
308         if (test.equals(test_1))
309             System.out.println("OK - dec_1");
310         else
311             System.out.println("TestDec=" + test_1 + " <> " + test);
312
313     // -----------------------------------------------------------------------
314

315         String JavaDoc testEnc = encrypt(test);
316         if (result.equals(testEnc))
317             System.out.println("OK - enc");
318         else
319             System.err.println("TestEnc=" + testEnc + " <> " + result);
320
321         String JavaDoc testDec = decrypt(testEnc);
322         if (test.equals(testDec))
323             System.out.println("OK - dec");
324         else
325             System.out.println("TestDec=" + testDec + " <> " + test);
326
327
328     } // main
329

330 } // Secure
331
Popular Tags