package org.loon.framework.game.simple.core;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;
/**
* Copyright 2008 - 2009
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* @project loonframework
* @author chenpeng
* @emailceponline@yahoo.com.cn
* @version 0.1
*/
public class LGUID {
public String valueBeforeMD5;
public String valueAfterMD5;
private static Random random;
private static SecureRandom mySecureRand;
private static String sid;
static {
mySecureRand = new SecureRandom();
long secureInitializer = mySecureRand.nextLong();
random = new Random(secureInitializer);
try {
sid = InetAddress.getLocalHost().toString();
} catch (UnknownHostException e) {
}
}
public LGUID() {
getRandomGUID(false);
}
public LGUID(boolean secure) {
getRandomGUID(secure);
}
private void getRandomGUID(boolean secure) {
MessageDigest md5 = null;
StringBuffer sbValueBeforeMD5 = new StringBuffer();
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
}
try {
long time = System.currentTimeMillis();
long rand = 0;
if (secure) {
rand = mySecureRand.nextLong();
} else {
rand = random.nextLong();
}
sbValueBeforeMD5.append(sid);
sbValueBeforeMD5.append(":");
sbValueBeforeMD5.append(Long.toString(time));
sbValueBeforeMD5.append(":");
sbValueBeforeMD5.append(Long.toString(rand));
valueBeforeMD5 = sbValueBeforeMD5.toString();
md5.update(valueBeforeMD5.getBytes());
byte[] array = md5.digest();
StringBuffer sb = new StringBuffer();
for (int j = 0; j < array.length; ++j) {
int b = array[j] & 0xFF;
if (b < 0x10)
sb.append('0');
sb.append(Integer.toHexString(b));
}
valueAfterMD5 = sb.toString();
} catch (Exception e) {
}
}
public String toString() {
String raw = valueAfterMD5.toUpperCase();
StringBuffer sb = new StringBuffer();
sb.append(raw.substring(0, 8));
sb.append("-");
sb.append(raw.substring(8, 12));
sb.append("-");
sb.append(raw.substring(12, 16));
sb.append("-");
sb.append(raw.substring(16, 20));
sb.append("-");
sb.append(raw.substring(20));
return sb.toString();
}
}
|