Source Code Cross Referenced for SecureRandom.java in  » 6.0-JDK-Modules » j2me » sun » security » provider » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » 6.0 JDK Modules » j2me » sun.security.provider 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * @(#)SecureRandom.java	1.17 06/10/10 
003:         *
004:         * Copyright  1990-2006 Sun Microsystems, Inc. All Rights Reserved.  
005:         * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER  
006:         *   
007:         * This program is free software; you can redistribute it and/or  
008:         * modify it under the terms of the GNU General Public License version  
009:         * 2 only, as published by the Free Software Foundation.   
010:         *   
011:         * This program is distributed in the hope that it will be useful, but  
012:         * WITHOUT ANY WARRANTY; without even the implied warranty of  
013:         * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU  
014:         * General Public License version 2 for more details (a copy is  
015:         * included at /legal/license.txt).   
016:         *   
017:         * You should have received a copy of the GNU General Public License  
018:         * version 2 along with this work; if not, write to the Free Software  
019:         * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  
020:         * 02110-1301 USA   
021:         *   
022:         * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa  
023:         * Clara, CA 95054 or visit www.sun.com if you need additional  
024:         * information or have any questions. 
025:         *
026:         */
027:
028:        package sun.security.provider;
029:
030:        import java.io.IOException;
031:        import java.security.MessageDigest;
032:        import java.security.SecureRandomSpi;
033:        import java.security.NoSuchAlgorithmException;
034:
035:        /**
036:         * <p>This class provides a crytpographically strong pseudo-random number
037:         * generator based on the SHA-1 hash algorithm.
038:         *
039:         * <p>Note that if a seed is not provided, we attempt to provide sufficient
040:         * seed bytes to completely randomize the internal state of the generator
041:         * (20 bytes).  However, our seed generation algorithm has not been thoroughly
042:         * studied or widely deployed.
043:         *
044:         * <p>Also note that when a random object is deserialized,
045:         * <a href="#engineNextBytes(byte[])">engineNextBytes</a> invoked on the
046:         * restored random object will yield the exact same (random) bytes as the
047:         * original object.  If this behaviour is not desired, the restored random
048:         * object should be seeded, using
049:         * <a href="#engineSetSeed(byte[])">engineSetSeed</a>.
050:         *
051:         * @version 1.10, 02/02/00
052:         * @author Benjamin Renaud
053:         * @author Josh Bloch
054:         * @author Gadi Guy
055:         */
056:
057:        public final class SecureRandom extends SecureRandomSpi implements 
058:                java.io.Serializable {
059:
060:            /**
061:             * This static object will be seeded by SeedGenerator, and used
062:             * to seed future instances of SecureRandom
063:             */
064:            private static SecureRandom seeder;
065:
066:            private static final int DIGEST_SIZE = 20;
067:            private transient MessageDigest digest;
068:            private byte[] state;
069:            private byte[] remainder;
070:            private int remCount;
071:
072:            /**
073:             * This empty constructor automatically seeds the generator.  We attempt
074:             * to provide sufficient seed bytes to completely randomize the internal
075:             * state of the generator (20 bytes).  Note, however, that our seed
076:             * generation algorithm has not been thoroughly studied or widely deployed.
077:             *
078:             * <p>The first time this constructor is called in a given Virtual Machine,
079:             * it may take several seconds of CPU time to seed the generator, depending
080:             * on the underlying hardware.  Successive calls run quickly because they
081:             * rely on the same (internal) pseudo-random number generator for their
082:             * seed bits.
083:             */
084:            public SecureRandom() {
085:                init(null);
086:            }
087:
088:            /**
089:             * This constructor is used to instatiate the private seeder object
090:             * with a given seed from the SeedGenerator.
091:             *
092:             * @param seed the seed.
093:             */
094:            private SecureRandom(byte seed[]) {
095:                init(seed);
096:            }
097:
098:            /**
099:             * This call, used by the constructors, instantiates the SHA digest
100:             * and sets the seed, if given.
101:             */
102:            private void init(byte[] seed) {
103:                try {
104:                    digest = MessageDigest.getInstance("SHA");
105:                } catch (NoSuchAlgorithmException e) {
106:                    throw new InternalError(
107:                            "internal error: SHA-1 not available.");
108:                }
109:
110:                if (seed != null) {
111:                    engineSetSeed(seed);
112:                }
113:            }
114:
115:            /**
116:             * Returns the given number of seed bytes, computed using the seed
117:             * generation algorithm that this class uses to seed itself.  This
118:             * call may be used to seed other random number generators.  While
119:             * we attempt to return a "truly random" sequence of bytes, we do not
120:             * know exactly how random the bytes returned by this call are.  (See
121:             * the empty constructor <a href = "#SecureRandom">SecureRandom</a>
122:             * for a brief description of the underlying algorithm.)
123:             * The prudent user will err on the side of caution and get extra
124:             * seed bytes, although it should be noted that seed generation is
125:             * somewhat costly.
126:             *
127:             * @param numBytes the number of seed bytes to generate.
128:             *
129:             * @return the seed bytes.
130:             */
131:            public byte[] engineGenerateSeed(int numBytes) {
132:                byte[] b = new byte[numBytes];
133:                SeedGenerator.generateSeed(b);
134:                return b;
135:            }
136:
137:            /**
138:             * Reseeds this random object. The given seed supplements, rather than
139:             * replaces, the existing seed. Thus, repeated calls are guaranteed
140:             * never to reduce randomness.
141:             *
142:             * @param seed the seed.
143:             */
144:            synchronized public void engineSetSeed(byte[] seed) {
145:                if (state != null) {
146:                    digest.update(state);
147:                    for (int i = 0; i < state.length; i++)
148:                        state[i] = 0;
149:                }
150:                state = digest.digest(seed);
151:            }
152:
153:            private static void updateState(byte[] state, byte[] output) {
154:                int last = 1;
155:                int v = 0;
156:                byte t = 0;
157:                boolean zf = false;
158:
159:                // state(n + 1) = (state(n) + output(n) + 1) % 2^160;
160:                for (int i = 0; i < state.length; i++) {
161:                    // Add two bytes
162:                    v = (int) state[i] + (int) output[i] + last;
163:                    // Result is lower 8 bits
164:                    t = (byte) v;
165:                    // Store result. Check for state collision.
166:                    zf = zf | (state[i] != t);
167:                    state[i] = t;
168:                    // High 8 bits are carry. Store for next iteration.
169:                    last = v >> 8;
170:                }
171:
172:                // Make sure at least one bit changes!
173:                if (!zf)
174:                    state[0]++;
175:            }
176:
177:            /**
178:             * Generates a user-specified number of random bytes.
179:             *
180:             * @param bytes the array to be filled in with random bytes.
181:             */
182:            public synchronized void engineNextBytes(byte[] result) {
183:                int index = 0;
184:                int todo;
185:                byte[] output = remainder;
186:
187:                if (state == null) {
188:                    if (seeder == null) {
189:                        seeder = new SecureRandom(SeedGenerator
190:                                .getSystemEntropy());
191:                        seeder.engineSetSeed(engineGenerateSeed(DIGEST_SIZE));
192:                    }
193:
194:                    byte[] seed = new byte[DIGEST_SIZE];
195:                    seeder.engineNextBytes(seed);
196:                    state = digest.digest(seed);
197:                }
198:
199:                // Use remainder from last time
200:                int r = remCount;
201:                if (r > 0) {
202:                    // How many bytes?
203:                    todo = (result.length - index) < (DIGEST_SIZE - r) ? (result.length - index)
204:                            : (DIGEST_SIZE - r);
205:                    // Copy the bytes, zero the buffer
206:                    for (int i = 0; i < todo; i++) {
207:                        result[i] = output[r];
208:                        output[r++] = 0;
209:                    }
210:                    remCount += todo;
211:                    index += todo;
212:                }
213:
214:                // If we need more bytes, make them.
215:                while (index < result.length) {
216:                    // Step the state
217:                    digest.update(state);
218:                    output = digest.digest();
219:                    updateState(state, output);
220:
221:                    // How many bytes?
222:                    todo = (result.length - index) > DIGEST_SIZE ? DIGEST_SIZE
223:                            : result.length - index;
224:                    // Copy the bytes, zero the buffer
225:                    for (int i = 0; i < todo; i++) {
226:                        result[index++] = output[i];
227:                        output[i] = 0;
228:                    }
229:                    remCount += todo;
230:                }
231:
232:                // Store remainder for next time
233:                remainder = output;
234:                remCount %= DIGEST_SIZE;
235:            }
236:
237:            /*
238:             * readObject is called to restore the state of the random object from
239:             * a stream.  We have to create a new instance of MessageDigest, because
240:             * it is not included in the stream (it is marked "transient").
241:             *
242:             * Note that the engineNextBytes() method invoked on the restored random
243:             * object will yield the exact same (random) bytes as the original.
244:             * If you do not want this behaviour, you should re-seed the restored
245:             * random object, using engineSetSeed().
246:             */
247:            private void readObject(java.io.ObjectInputStream s)
248:                    throws IOException, ClassNotFoundException {
249:
250:                s.defaultReadObject();
251:
252:                try {
253:                    digest = MessageDigest.getInstance("SHA");
254:                } catch (NoSuchAlgorithmException e) {
255:                    throw new InternalError(
256:                            "internal error: SHA-1 not available.");
257:                }
258:            }
259:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.