01: /*
02: * Created on Nov 23, 2004
03: */
04: package uk.org.ponder.hashutil;
05:
06: import java.security.SecureRandom;
07:
08: import uk.org.ponder.stringutil.ByteToCharBase64;
09: import uk.org.ponder.stringutil.CharWrap;
10:
11: /**
12: * Generates a unique ID composed of printable characters. 24 characters
13: * are quasi-base-64-encoded from 18 random bytes
14: * generated by a good (in this case java.util.SecureRandom) random number
15: * generator. In case anyone is worried about the possibilities of collision
16: * of these IDs over time, the formula for probability of non-collision is
17: * $p = e^{-n^2/2k}$. Inverting and approximating for small p we gain
18: * $n = \sqrt{2k/p}$. For 144 bits of hash (~ 10^43), if we ask how many
19: * pages (resources) must be generated before the probability of collision
20: * reaches 1 in a billion (10^-9), we require ~ 10^17 hashes, i.e. 200Pb of
21: * pages if only one byte per page.
22: *
23: * This class is threadsafe, at the moment since SecureRandom is synchronized.
24: *
25: * @author Antranig Basman (antranig@caret.cam.ac.uk)
26: */
27: public class EighteenIDGenerator implements IDGenerator {
28: SecureRandom random = new SecureRandom();
29:
30: public String generateID() {
31: byte[] eighteen = new byte[18];
32: random.nextBytes(eighteen);
33: CharWrap togo = new CharWrap();
34: ByteToCharBase64.writeBytes(togo, eighteen, 0, 18, false);
35: return togo.toString();
36: }
37:
38: }
|