1 16 package org.directwebremoting.util; 17 18 import java.security.MessageDigest ; 19 import java.security.NoSuchAlgorithmException ; 20 import java.security.SecureRandom ; 21 import java.util.Random ; 22 23 33 public class IdGenerator 34 { 35 38 public IdGenerator() 39 { 40 long seed = System.currentTimeMillis(); 42 43 char[] entropy = this.toString().toCharArray(); 45 for (int i = 0; i < entropy.length; i++) 46 { 47 long update = ((byte) entropy[i]) << ((i % 8) * 8); 48 seed ^= update; 49 } 50 51 random.setSeed(seed); 52 } 53 54 59 public synchronized String generateId(int length) 60 { 61 byte buffer[] = new byte[16]; 62 63 StringBuffer reply = new StringBuffer (); 65 66 int resultLenBytes = 0; 67 while (resultLenBytes < length) 68 { 69 random.nextBytes(buffer); 70 buffer = getDigest().digest(buffer); 71 72 for (int j = 0; j < buffer.length && resultLenBytes < length; j++) 73 { 74 byte b1 = (byte) ((buffer[j] & 0xf0) >> 4); 75 if (b1 < 10) 76 { 77 reply.append((char) ('0' + b1)); 78 } 79 else 80 { 81 reply.append((char) ('A' + (b1 - 10))); 82 } 83 84 byte b2 = (byte) (buffer[j] & 0x0f); 85 if (b2 < 10) 86 { 87 reply.append((char) ('0' + b2)); 88 } 89 else 90 { 91 reply.append((char) ('A' + (b2 - 10))); 92 } 93 94 resultLenBytes++; 95 } 96 } 97 98 return reply.toString(); 99 } 100 101 104 public synchronized String getAlgorithm() 105 { 106 return algorithm; 107 } 108 109 112 public synchronized void setAlgorithm(String algorithm) 113 { 114 this.algorithm = algorithm; 115 digest = null; 116 } 117 118 124 private MessageDigest getDigest() 125 { 126 if (digest == null) 127 { 128 try 129 { 130 digest = MessageDigest.getInstance(algorithm); 131 } 132 catch (NoSuchAlgorithmException ex) 133 { 134 try 135 { 136 digest = MessageDigest.getInstance(DEFAULT_ALGORITHM); 137 } 138 catch (NoSuchAlgorithmException ex2) 139 { 140 digest = null; 141 throw new IllegalStateException ("No algorithms for IdGenerator"); 142 } 143 } 144 145 log.debug("Using MessageDigest: " + digest.getAlgorithm()); 146 } 147 148 return digest; 149 } 150 151 154 public String toString() 155 { 156 return super.toString(); 160 } 161 162 166 protected static final String DEFAULT_ALGORITHM = "MD5"; 167 168 173 protected String algorithm = DEFAULT_ALGORITHM; 174 175 178 protected Random random = new SecureRandom (); 179 180 184 protected MessageDigest digest = null; 185 186 189 private static final Logger log = Logger.getLogger(IdGenerator.class); 190 } 191 | Popular Tags |