Java tutorial
/******************************************************************************* * Copyright 2009, 2010 Innovation Gate GmbH * * 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. ******************************************************************************/ package de.innovationgate.utils; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.apache.commons.lang.RandomStringUtils; /** * All-purpose generator for unique IDs. * The IDs generated by this class are based on a random 64 character string * and the current system time, hashed by MD5. The resulting string is * a 32 character hexadecimal value. * */ public class UIDGenerator { /** * Generate a unique ID */ public static String generateUID() { String randomString = RandomStringUtils.randomAlphanumeric(64); String hashString = randomString + System.currentTimeMillis(); return generateMD5Hash(hashString); } /** * Generates an MD5 hash from the given string * @param hashString */ public static String generateMD5Hash(String hashString) { MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { return null; } md5.update(hashString.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)); } return sb.toString(); } }