KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > h2 > util > RandomUtils


1 /*
2  * Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
3  * Initial Developer: H2 Group
4  */

5 package org.h2.util;
6
7 import java.security.NoSuchAlgorithmException JavaDoc;
8 import java.security.SecureRandom JavaDoc;
9 import java.util.Random JavaDoc;
10
11 public class RandomUtils {
12     private static SecureRandom JavaDoc secureRandom;
13     private static Random JavaDoc random;
14
15     static {
16         try {
17             secureRandom = SecureRandom.getInstance("SHA1PRNG");
18             random = new Random JavaDoc(secureRandom.nextLong());
19         } catch (NoSuchAlgorithmException JavaDoc e) {
20             // random is null if the algorithm is not found
21
// TODO log exception
22
random = new Random JavaDoc();
23         }
24     }
25     
26     public static long getSecureLong() {
27         if(secureRandom == null) {
28             byte[] buff = SecureRandom.getSeed(8);
29             return ByteUtils.readLong(buff, 0);
30         }
31         return secureRandom.nextLong();
32     }
33     
34     
35
36     public static byte[] getSecureBytes(int len) {
37         if(secureRandom == null) {
38             return SecureRandom.getSeed(len);
39         }
40         if(len <= 0) {
41             len = 1;
42         }
43         byte[] buff = new byte[len];
44         secureRandom.nextBytes(buff);
45         return buff;
46     }
47
48     public static int nextInt(int max) {
49         return random.nextInt(max);
50     }
51
52 }
53
Popular Tags