KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jmanage > core > crypto > Crypto


1 /**
2  * Copyright 2004-2005 jManage.org
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.jmanage.core.crypto;
17
18 import org.jmanage.core.util.Loggers;
19 import org.jmanage.core.util.JManageProperties;
20
21 import javax.crypto.*;
22 import java.security.MessageDigest JavaDoc;
23 import java.security.NoSuchAlgorithmException JavaDoc;
24 import java.util.logging.Logger JavaDoc;
25
26 /**
27  * Crypto acts as a facade layer for the crypto classes.
28  *
29  * Note that the crypto functions must not be called directly from CLI. This
30  * is because server has the crypto keys and the crypto configuration.
31  *
32  * date: Jul 23, 2004
33  * @author Rakesh Kalra
34  */

35 public class Crypto {
36
37     private static final Logger JavaDoc logger = Loggers.getLogger(Crypto.class);
38
39     /* get the hashing algorithm from jmanage.properties */
40     private static final String JavaDoc hashAlgorithm =
41             JManageProperties.getHashAlgorithm();
42
43     private static Cipher encrypter;
44     private static Cipher decrypter;
45
46     public static void init(char[] password){
47         EncryptedKey encryptedKey = KeyManager.readKey(password);
48         SecretKey secretKey = encryptedKey.getSecretKey();
49         encrypter = getCipher(Cipher.ENCRYPT_MODE, secretKey);
50         assert encrypter != null;
51         decrypter = getCipher(Cipher.DECRYPT_MODE, secretKey);
52         assert decrypter != null;
53         logger.info("Crypto initialized");
54     }
55
56     public static synchronized byte[] encrypt(String JavaDoc plaintext){
57         try {
58             return encrypter.doFinal(plaintext.getBytes());
59         } catch (Exception JavaDoc e) {
60             throw new RuntimeException JavaDoc(e);
61         }
62     }
63
64     public static String JavaDoc encryptToString(String JavaDoc plaintext){
65         byte[] ciphertext = encrypt(plaintext);
66         return byteArrayToHexString(ciphertext);
67     }
68
69     public static synchronized byte[] decrypt(byte[] ciphertext){
70         try {
71             return decrypter.doFinal(ciphertext);
72         } catch (Exception JavaDoc e) {
73             throw new RuntimeException JavaDoc(e);
74         }
75     }
76
77     public static String JavaDoc decrypt(String JavaDoc ciphertext){
78         byte[] plaintext = decrypt(hexStringToByteArray(ciphertext));
79         return new String JavaDoc(plaintext);
80     }
81
82     /**
83      * hash method can be used without calling init() method on Crypto.
84      *
85      * @param plaintext
86      * @return
87      */

88     public static String JavaDoc hash(String JavaDoc plaintext){
89         return hash(plaintext.toCharArray());
90     }
91
92     public static String JavaDoc hash(char[] plaintext){
93         try {
94             MessageDigest JavaDoc sha = MessageDigest.getInstance(hashAlgorithm);
95             byte[] hash = sha.digest(charArrayToByteArray(plaintext));
96             return byteArrayToHexString(hash);
97         } catch (NoSuchAlgorithmException JavaDoc e) {
98             throw new RuntimeException JavaDoc(e);
99         }
100     }
101
102     private static Cipher getCipher(int mode, SecretKey secretKey){
103
104         try {
105             Cipher cipher = Cipher.getInstance(EncryptedKey.CRYPTO_ALGORITHM);
106             cipher.init(mode, secretKey);
107             return cipher;
108         } catch (Exception JavaDoc e) {
109             throw new RuntimeException JavaDoc(e);
110         }
111     }
112
113     private static byte[] charArrayToByteArray(char[] array){
114         final byte[] output = new byte[array.length];
115         for(int i=0; i<output.length; i++){
116             output[i] = (byte) array[i];
117         }
118         return output;
119     }
120
121     private static String JavaDoc byteArrayToHexString(byte[] ba)
122     {
123         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(ba.length * 2);
124         int n = ba.length;
125         for (int i = 0; i < n; i++) {
126             byte b = ba[i];
127             appendASCII(b, buffer);
128         }
129         return buffer.toString();
130     }
131
132     private static byte[] hexStringToByteArray(String JavaDoc s) {
133         char[] ca = s.toCharArray();
134         int n_chars = ca.length;
135         byte[] ba = new byte[n_chars / 2];
136         int ci = 0;
137         int bi = 0;
138         while (ci < n_chars) {
139             char c = ca[ci++];
140             byte hi = hexCharToByte(c);
141             c = ca[ci++];
142             byte lo = hexCharToByte(c);
143             ba[bi++] = (byte) ((hi << 4) | lo);
144         }
145         return ba;
146     }
147
148     private static void appendASCII(byte b, StringBuffer JavaDoc buffer) {
149         byte hi = (byte) ((b >> 4) & 0xf);
150         byte lo = (byte) (b & 0xf);
151         buffer.append(hexByteToChar(hi));
152         buffer.append(hexByteToChar(lo));
153     }
154
155     private static char hexByteToChar(byte b) {
156         char c = 0;
157         switch (b)
158         {
159         case 0x0: c = '0'; break;
160         case 0x1: c = '1'; break;
161         case 0x2: c = '2'; break;
162         case 0x3: c = '3'; break;
163         case 0x4: c = '4'; break;
164         case 0x5: c = '5'; break;
165         case 0x6: c = '6'; break;
166         case 0x7: c = '7'; break;
167         case 0x8: c = '8'; break;
168         case 0x9: c = '9'; break;
169         case 0xa: c = 'a'; break;
170         case 0xb: c = 'b'; break;
171         case 0xc: c = 'c'; break;
172         case 0xd: c = 'd'; break;
173         case 0xe: c = 'e'; break;
174         case 0xf: c = 'f'; break;
175         default: assert false:"Bad byte digit of '" + c + "' received"; break;
176         }
177         return c;
178     }
179
180     private static byte hexCharToByte(char c) {
181         byte b = 0;
182         switch (c)
183         {
184         case '0': b = 0x0; break;
185         case '1': b = 0x1; break;
186         case '2': b = 0x2; break;
187         case '3': b = 0x3; break;
188         case '4': b = 0x4; break;
189         case '5': b = 0x5; break;
190         case '6': b = 0x6; break;
191         case '7': b = 0x7; break;
192         case '8': b = 0x8; break;
193         case '9': b = 0x9; break;
194         case 'a': case 'A': b = 0xa; break;
195         case 'b': case 'B': b = 0xb; break;
196         case 'c': case 'C': b = 0xc; break;
197         case 'd': case 'D': b = 0xd; break;
198         case 'e': case 'E': b = 0xe; break;
199         case 'f': case 'F': b = 0xf; break;
200         default: assert false:"Bad hex digit of '" + c + "' received"; break;
201         }
202         return b;
203     }
204 }
205
Popular Tags