1 15 package org.columba.core.base; 16 17 import java.security.SecureRandom ; 18 19 26 public class UUIDGenerator { 27 28 31 private final SecureRandom secRand = new SecureRandom (); 32 33 36 private final byte[] secRandBuf16 = new byte[16]; 37 38 public UUIDGenerator() { 39 super(); 40 } 41 42 45 public String newUUID() { 46 secRand.nextBytes(secRandBuf16); 47 secRandBuf16[6] &= 0x0f; 48 secRandBuf16[6] |= 0x40; 49 secRandBuf16[8] &= 0x3f; 50 secRandBuf16[8] |= 0x80; 51 secRandBuf16[10] |= 0x80; 52 long mostSig = 0; 53 for (int i = 0; i < 8; i++) { 54 mostSig = (mostSig << 8) | (secRandBuf16[i] & 0xff); 55 } 56 long leastSig = 0; 57 for (int i = 8; i < 16; i++) { 58 leastSig = (leastSig << 8) | (secRandBuf16[i] & 0xff); 59 } 60 return (digits(mostSig >> 32, 8) + "-" + digits(mostSig >> 16, 4) + "-" + digits(mostSig, 4) + "-" + digits(leastSig >> 48, 4) + "-" + digits( leastSig, 12)); 63 } 64 65 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 } 72 | Popular Tags |