KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > jcetaglib > lib > Keystore


1 /*
2   Name: Keystore.java
3   Licensing: LGPL
4
5   API: Sun (http://java.sun.com) JCE 1.2.2 API (cleanroom implementation by Bouncy Castle)
6   Provider: Bouncy Castle (http://www.bouncycastle.org)
7
8   Disclaimer:
9
10   COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY OF ANY KIND,
11   EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE
12   IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE
13   RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE IS WITH YOU. SHOULD ANY COVERED CODE
14   PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR)
15   ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY
16   CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED
17   HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
18
19   (C) Copyright 2003 Gert Van Ham
20 */

21
22 package net.sourceforge.jcetaglib.lib;
23
24 import net.sourceforge.jcetaglib.exceptions.KeystoreException;
25 import org.bouncycastle.jce.provider.BouncyCastleProvider;
26
27 import javax.crypto.Cipher;
28 import javax.crypto.KeyGenerator;
29 import javax.crypto.SecretKey;
30 import javax.crypto.SecretKeyFactory;
31 import javax.crypto.spec.PBEKeySpec;
32 import javax.crypto.spec.PBEParameterSpec;
33 import java.io.ByteArrayOutputStream JavaDoc;
34 import java.io.FileInputStream JavaDoc;
35 import java.io.FileOutputStream JavaDoc;
36 import java.io.IOException JavaDoc;
37 import java.security.Key JavaDoc;
38 import java.security.SecureRandom JavaDoc;
39 import java.security.Security JavaDoc;
40
41 /**
42  * Load & generate symmetric keystores
43  *
44  * @author Gert Van Ham
45  * @author hamgert@users.sourceforge.net
46  * @author http://jcetaglib.sourceforge.net
47  * @version $Id: Keystore.java,v 1.3 2004/04/15 07:28:25 hamgert Exp $
48  */

49 public class Keystore {
50
51     // secret key keystore parameters
52
static final String JavaDoc SECRET_KEYSTORE_ALGORITHM = "PBEWithSHAAndTwofish-CBC";
53     static final int SECRET_KEYSTORE_COUNT = 100;
54
55     /**
56      * Generates a secret (= symmetric) key object and store it in a file
57      *
58      * @param algorithm encryption algorithm (e.g. "Rijndael")
59      * @param strength the keysize in bits (e.g. 128)
60      * @param seed seed for SecureRandom (optional)
61      * @param file the file(name) to store the key
62      * @param passphrase the passphrase for the keystore
63      * @throws KeystoreException for all errors
64      **/

65     public static void generateKey(String JavaDoc algorithm
66                                    , int strength
67                                    , byte[] seed
68                                    , String JavaDoc file
69                                    , StringBuffer JavaDoc passphrase)
70             throws KeystoreException {
71
72         KeyGenerator kg = null;
73         Key key;
74         PBEKeySpec pbeKeySpec;
75         PBEParameterSpec pbeParamSpec;
76         SecretKeyFactory keyFac;
77         SecretKey pbeKey;
78         Cipher pbeCipher;
79         FileOutputStream JavaDoc fos = null;
80
81         try {
82
83             Security.addProvider(new BouncyCastleProvider());
84             SecureRandom JavaDoc sr = Seed.getSecureRandom(seed);
85
86             // get a key generator for the algorithm.
87
kg = KeyGenerator.getInstance(algorithm, "BC");
88             kg.init(strength, sr);
89
90             // create a secret key from the keygenerator.
91
key = kg.generateKey();
92
93             // secure the new key with PBE encryption
94

95             // Create a random salt of 64 bits (8 bytes)
96
byte[] randomsalt = new byte[8];
97             sr.nextBytes(randomsalt);
98
99             // Create PBE parameter set
100
pbeParamSpec = new PBEParameterSpec(randomsalt, SECRET_KEYSTORE_COUNT);
101
102             pbeKeySpec = new PBEKeySpec(passphrase.toString().toCharArray());
103             keyFac = SecretKeyFactory.getInstance(SECRET_KEYSTORE_ALGORITHM);
104             pbeKey = keyFac.generateSecret(pbeKeySpec);
105
106             // Create PBE Cipher
107
pbeCipher = Cipher.getInstance(SECRET_KEYSTORE_ALGORITHM);
108
109             // wrap the block cipher key
110
pbeCipher.init(Cipher.WRAP_MODE, pbeKey, pbeParamSpec);
111             byte[] wrappedKey = pbeCipher.wrap(key);
112
113             // save the wrapped key to disk
114
fos = new FileOutputStream JavaDoc(file);
115             fos.write(randomsalt);
116             fos.write(wrappedKey);
117         } catch (Exception JavaDoc ex) {
118             ex.printStackTrace();
119             throw new KeystoreException(ex.getMessage());
120         } finally {
121             // close the file
122
if (fos != null) {
123                 try {
124                     fos.close();
125                 } catch (IOException JavaDoc ioe) {
126                     ;
127                 }
128             }
129
130             // cleanup
131
key = null;
132             pbeKey = null;
133             Clean.blank(passphrase);
134             passphrase = null;
135         }
136     }
137
138     /**
139      * Load the secret (= symmetric) key object from the keystore
140      *
141      * @param algorithm String encryption algorithm (e.g. "Rijndael")
142      * @param file String the keystore file(name)
143      * @param passphrase StringBuffer the passphrase for the keystore
144      * @return Keystore secretkey object
145      * @throws KeystoreException for all errors
146      **/

147     public static Key loadKey(String JavaDoc algorithm
148                               , String JavaDoc file
149                               , StringBuffer JavaDoc passphrase)
150             throws KeystoreException {
151
152         FileInputStream JavaDoc fInput = null;
153         ByteArrayOutputStream JavaDoc baos = null;
154         PBEKeySpec pbeKeySpec;
155         PBEParameterSpec pbeParamSpec;
156         SecretKeyFactory keyFac;
157         SecretKey pbeKey;
158         Cipher pbeCipher;
159         Key newkey;
160
161         try {
162             // Add Bouncy Castle provider
163
Security.addProvider(new BouncyCastleProvider());
164
165             fInput = new FileInputStream JavaDoc(file);
166
167             // read the salt
168
byte[] randomsalt = new byte[8];
169             fInput.read(randomsalt);
170
171             // read the wrapped key
172
baos = new ByteArrayOutputStream JavaDoc();
173             int i = 0;
174             while ((i = fInput.read()) != -1) {
175                 baos.write(i);
176             }
177
178             byte[] wrappedKey = baos.toByteArray();
179
180             // Create PBE parameter set
181
pbeParamSpec = new PBEParameterSpec(randomsalt, SECRET_KEYSTORE_COUNT);
182
183             pbeKeySpec = new PBEKeySpec(passphrase.toString().toCharArray());
184             keyFac = SecretKeyFactory.getInstance(SECRET_KEYSTORE_ALGORITHM);
185             pbeKey = keyFac.generateSecret(pbeKeySpec);
186
187             // Create PBE Cipher
188
pbeCipher = Cipher.getInstance(SECRET_KEYSTORE_ALGORITHM);
189
190             // Unwrap the key
191
pbeCipher.init(Cipher.UNWRAP_MODE, pbeKey, pbeParamSpec);
192             newkey = pbeCipher.unwrap(wrappedKey, algorithm, Cipher.SECRET_KEY);
193
194             return newkey;
195         } catch (Exception JavaDoc ex) {
196             ex.printStackTrace();
197             throw new KeystoreException(ex.getMessage());
198         } finally {
199             // close the file
200
if (fInput != null) {
201                 try {
202                     fInput.close();
203                 } catch (IOException JavaDoc ioe) {
204                     ;
205                 }
206             }
207             // close the outputstream
208
if (baos != null) {
209                 try {
210                     baos.close();
211                 } catch (IOException JavaDoc ioe) {
212                     ;
213                 }
214             }
215             // cleanup
216
pbeKey = null;
217             Clean.blank(passphrase);
218             passphrase = null;
219         }
220     }
221 }
222
Popular Tags