1 5 package org.h2.util; 6 7 import java.security.NoSuchAlgorithmException ; 8 import java.security.SecureRandom ; 9 import java.util.Random ; 10 11 public class RandomUtils { 12 private static SecureRandom secureRandom; 13 private static Random random; 14 15 static { 16 try { 17 secureRandom = SecureRandom.getInstance("SHA1PRNG"); 18 random = new Random (secureRandom.nextLong()); 19 } catch (NoSuchAlgorithmException e) { 20 random = new Random (); 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 |