01: /**
02: *
03: * Copyright 2001 Sun Microsystems(TM), Inc. All Rights Reserved.
04: *
05: * The contents of this file are made available under and subject to the
06: * Research Use Rights of the Sun(TM) Community Source License v 3.0 (the
07: * "License"). Software distributed under the License is distributed on an "AS
08: * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
09: * License for the specific language governing rights and limitations under
10: * the License.
11: *
12: * Contributor(s): Sun Microsystems, Inc.
13: *
14: */package org.columba.calendar.base;
15:
16: import java.security.SecureRandom;
17:
18: /**
19: * A universally unique identifier (UUID). A UUID is a 128-bit value.
20: * <p>
21: * Standard RFC:
22: * http://www.ietf.org/internet-drafts/draft-mealling-uuid-urn-05.txt
23: * <p>
24: */
25: public class UUIDGenerator {
26:
27: /**
28: * random number generator for UUID generation
29: */
30: private final SecureRandom secRand = new SecureRandom();
31:
32: /**
33: * 128-bit buffer for use with secRand
34: */
35: private final byte[] secRandBuf16 = new byte[16];
36:
37: public UUIDGenerator() {
38: super ();
39: }
40:
41: /**
42: * @return uuid as String
43: */
44: public String newUUID() {
45: secRand.nextBytes(secRandBuf16);
46: secRandBuf16[6] &= 0x0f;
47: secRandBuf16[6] |= 0x40; /* version 4 */
48: secRandBuf16[8] &= 0x3f;
49: secRandBuf16[8] |= 0x80; /* IETF variant */
50: secRandBuf16[10] |= 0x80; /* multicast bit */
51: long mostSig = 0;
52: for (int i = 0; i < 8; i++) {
53: mostSig = (mostSig << 8) | (secRandBuf16[i] & 0xff);
54: }
55: long leastSig = 0;
56: for (int i = 8; i < 16; i++) {
57: leastSig = (leastSig << 8) | (secRandBuf16[i] & 0xff);
58: }
59: return (digits(mostSig >> 32, 8) + "-"
60: + digits(mostSig >> 16, 4) + "-" + digits(mostSig, 4)
61: + "-" + digits(leastSig >> 48, 4) + "-" + digits(
62: leastSig, 12));
63: }
64:
65: /** Returns val represented by the specified number of hex digits. */
66: private static String digits(long val, int digits) {
67: long hi = 1L << (digits * 4);
68: return Long.toHexString(hi | (val & (hi - 1))).substring(1);
69: }
70:
71: }
|