1 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 ; 72 import java.io.FileInputStream ; 73 import java.io.FileNotFoundException ; 74 import java.io.FileOutputStream ; 75 import java.io.IOException ; 76 import java.io.InputStream ; 77 import java.io.OutputStream ; 78 import java.security.NoSuchAlgorithmException ; 79 import java.security.SecureRandom ; 80 81 82 89 public final class RandomNumber 90 extends AbstractRandomNumber { 91 private SecureRandom secRand = null; 92 String 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 106 public RandomNumber() 107 throws ChainedException { 108 } 109 110 111 117 public void init() throws ChainedException { 118 try { 119 byte seed[] = null; 120 121 String configDir = this.getCryptoManager().getRandomSeed(); 122 seedFile = configDir + "/random.seed"; 123 File f = new File (seedFile); 124 if (f.exists()) { 125 try { 126 InputStream s = new FileInputStream (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 ex) { 133 if (log.isDebugEnabled()) { 134 log.debug("File not found exception loading random seed.", ex); 135 } 136 } catch (java.io.IOException 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 os = new FileOutputStream (f); 152 os.write(seed); 153 } catch (IOException ex) { 154 log.warn("Unable to write random.seed file to config directory", ex); 155 } 156 157 158 return; 159 } catch (NoSuchAlgorithmException 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 174 public byte[] getRandomBytes(int numBytes) { 175 byte[] newBytes = new byte[numBytes]; 176 secRand.nextBytes(newBytes); 177 178 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 os = new FileOutputStream (new File (seedFile)); 189 os.write(seed); 190 } catch (IOException ex) { 191 System.err.println("Unable to write random.seed file to config directory"); 192 } 193 } 194 195 return newBytes; 196 } 197 198 } 199 200 201
| Popular Tags
|