KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > core > security > strongencryption > RandomNumber


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.strongencryption;
66
67 import com.jcorporate.expresso.core.security.AbstractRandomNumber;
68 import com.jcorporate.expresso.kernel.exception.ChainedException;
69 import org.apache.log4j.Logger;
70
71 import java.io.File JavaDoc;
72 import java.io.FileInputStream JavaDoc;
73 import java.io.FileNotFoundException JavaDoc;
74 import java.io.FileOutputStream JavaDoc;
75 import java.io.IOException JavaDoc;
76 import java.io.InputStream JavaDoc;
77 import java.io.OutputStream JavaDoc;
78 import java.security.NoSuchAlgorithmException JavaDoc;
79 import java.security.SecureRandom JavaDoc;
80
81
82 /**
83  * Cryptographically Strong Version of the random number generator.
84  * Due to the seeding process, the constructor for this class will
85  * take a significant amount of time to initialize.
86  *
87  * @author Michael Rimov
88  */

89 public final class RandomNumber
90         extends AbstractRandomNumber {
91     private SecureRandom JavaDoc secRand = null;
92     String JavaDoc seedFile = null;
93     int call_count = 0;
94
95     private static final int SEED_LENGTH = 256;
96
97
98     private static final Logger log = Logger.getLogger(RandomNumber.class);
99
100     /**
101      * Default Constructor
102      *
103      * @throws ChainedException if unable to instantiate the SHA1 Random
104      * number generator
105      */

106     public RandomNumber()
107             throws ChainedException {
108     } /* RandomNumber() */
109
110
111     /**
112      * To save some time, we use the last seed generated from a file instead
113      * of loading from scratch
114      *
115      * @throws NoSuchAlgorithmException if we cannot find the SHA1PRNG
116      */

117     public void init() throws ChainedException {
118         try {
119             byte seed[] = null;
120
121             String JavaDoc configDir = this.getCryptoManager().getRandomSeed();
122             seedFile = configDir + "/random.seed";
123             File JavaDoc f = new File JavaDoc(seedFile);
124             if (f.exists()) {
125                 try {
126                     InputStream JavaDoc s = new FileInputStream JavaDoc(f);
127                     seed = new byte[SEED_LENGTH];
128                     int numRead = s.read(seed, 0, SEED_LENGTH);
129                     if (numRead < SEED_LENGTH) {
130                         seed = null;
131                     }
132                 } catch (FileNotFoundException JavaDoc ex) {
133                     if (log.isDebugEnabled()) {
134                         log.debug("File not found exception loading random seed.", ex);
135                     }
136                 } catch (java.io.IOException JavaDoc ex) {
137                     if (log.isDebugEnabled()) {
138                         log.debug("I/O exception loading random seed.", ex);
139                     }
140                 }
141             }
142
143             secRand = SecureRandom.getInstance("SHA1PRNG");
144             if (seed != null) {
145                 secRand.setSeed(seed);
146             }
147             seed = new byte[SEED_LENGTH];
148             secRand.nextBytes(seed);
149
150             try {
151                 OutputStream JavaDoc os = new FileOutputStream JavaDoc(f);
152                 os.write(seed);
153             } catch (IOException JavaDoc ex) {
154                 log.warn("Unable to write random.seed file to config directory", ex);
155             }
156
157
158             return;
159         } catch (NoSuchAlgorithmException JavaDoc ex) {
160             throw new ChainedException("com.javacocporate.common.security.strongencryption.RandomNumber." +
161                     "RandomNumber()" +
162                     " Unable to load algorithm SHA1PRNG. Your " +
163                     "version of the JDK may not support this" + " method.", ex);
164         }
165     }
166
167     /**
168      * getRandomBytes - Returns a byte array of random bytes. The derived
169      * class determines the actual method used for getting the random data.
170      *
171      * @param numBytes The number of bytes to retrieve
172      * @return An array of random bytes
173      */

174     public byte[] getRandomBytes(int numBytes) {
175         byte[] newBytes = new byte[numBytes];
176         secRand.nextBytes(newBytes);
177
178         //
179
//Write a new seed file every ten calls to getRandomBytes
180
//
181
call_count = (call_count++) % 10;
182
183         if (call_count == 0) {
184             byte seed[] = new byte[SEED_LENGTH];
185             secRand.nextBytes(seed);
186
187             try {
188                 OutputStream JavaDoc os = new FileOutputStream JavaDoc(new File JavaDoc(seedFile));
189                 os.write(seed);
190             } catch (IOException JavaDoc ex) {
191                 System.err.println("Unable to write random.seed file to config directory");
192             }
193         }
194
195         return newBytes;
196     } /* getRandomBytes(int) */
197
198 } /* RandomNumber */
199
200 /* RandomNumber */
201
Free Books   Free Magazines  
Popular Tags