在我java
程序,我需要生成一個unique order number
爲customer's order
。我認爲time of creation of order
是一個足夠好的獨特的價值。 Two orders cannot be created at the same second
。 爲了防止他人使用訂單號,通過猜測某些創作時間值,我將創建時間字符串的一部分hash
添加到它,並將其作爲最終訂單號字符串。出獨特而有序,對顧客的訂單訂單號
是否有這種做法的任何看不見的陷阱?創建基於創建時間的順序號是爲了給某種順序在系統中創建的訂單.. 的代碼這裏給出
public static String createOrderNumber(Date orderDate) throws NoSuchAlgorithmException {
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String datestring = df.format(orderDate).toString();
System.out.println("datestring="+datestring);
System.out.println("datestring size="+datestring.length());
String hash = makeHashString(datestring);//creates SHA1 hash of 16 digits
System.out.println("hash="+hash);
System.out.println("hash size="+hash.length());
int datestringlen = datestring.length();
String ordernum = datestring+hash.substring(datestringlen,datestringlen+5);
System.out.println("ordernum size="+ordernum.length());
return ordernum;
}
private static String makeHashString(String plain) throws NoSuchAlgorithmException {
final int MD_PASSWORD_LENGTH = 16;
final String HASH_ALGORITHM = "SHA1";
String hash = null;
try {
MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM);
md.update(plain.getBytes());
BigInteger hashint = new BigInteger(1, md.digest());
hash = hashint.toString(MD_PASSWORD_LENGTH);
} catch (NoSuchAlgorithmException nsae) {
throw(nsae);
}
return hash;
}
樣本輸出爲
datestring=20110924103251
datestring size=14
hash=a9bcd51fc69d9225c5d96061d9c8628137df14e0
hash size=40
ordernum size=19
ordernum=2011092410325125c5d
*「兩個訂單不能在同一秒創建」*如果服務器每秒處理20個訂單,它們可以。 –