1 13 14 package org.ejbca.core.ejb.ca.sign; 15 16 import java.math.BigInteger ; 17 import java.security.SecureRandom ; 18 import java.util.Date ; 19 20 import org.apache.log4j.Logger; 21 import org.ejbca.core.model.InternalResources; 22 23 24 42 public class SernoGenerator implements ISernoGenerator { 43 44 private static Logger log = Logger.getLogger(SernoGenerator.class); 45 46 private static final InternalResources intres = InternalResources.getInstance(); 47 48 49 private static String algorithm = "SHA1PRNG"; 50 51 52 private SecureRandom random; 53 54 55 private static SernoGenerator instance = null; 56 57 private static final BigInteger lowest = new BigInteger ("0080000000000000", 16); 58 private static final BigInteger highest = new BigInteger ("7FFFFFFFFFFFFFFF", 16); 59 60 63 protected SernoGenerator() throws Exception { 64 log.debug(">SernoGenerator()"); 65 66 random = SecureRandom.getInstance(algorithm); 68 69 long seed = Math.abs((new Date ().getTime()) + this.hashCode()); 76 random.setSeed(seed); 77 78 96 log.debug("<SernoGenerator()"); 97 } 98 99 104 public static synchronized ISernoGenerator instance() 105 throws Exception { 106 if (instance == null) { 107 instance = new SernoGenerator(); 108 } 109 return instance; 110 } 111 112 117 public synchronized BigInteger getSerno() { 118 byte[] sernobytes = new byte[8]; 119 boolean ok = false; 120 BigInteger serno = null; 121 while (!ok) { 122 random.nextBytes(sernobytes); 123 serno = (new java.math.BigInteger (sernobytes)).abs(); 124 if ( (serno.compareTo(lowest) >= 0) && (serno.compareTo(highest) <= 0) ) { 126 ok = true; 127 } else { 128 String msg = intres.getLocalizedMessage("sernogenerator.discarding"); 129 log.info(msg); 130 } 131 } 132 return serno; 133 } 134 135 140 public int getNoSernoBytes() { 141 return 8; 142 } 143 144 152 public void setSeed(long seed) { 153 random.setSeed(seed); 154 } 155 156 159 public static void setAlgorithm(String algo) { 160 algorithm = algo; 161 } 162 } 163 | Popular Tags |