Skip to content

Instantly share code, notes, and snippets.

@McKay1717
Created August 18, 2014 21:23
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save McKay1717/f896f98ed8c4508236b8 to your computer and use it in GitHub Desktop.
Save McKay1717/f896f98ed8c4508236b8 to your computer and use it in GitHub Desktop.
PHP uniqid in JAVA
public class Uniqid {
/***
* Copy of uniqid in php http://php.net/manual/fr/function.uniqid.php
* @param prefix
* @param more_entropy
* @return
*/
public String uniqid(String prefix,boolean more_entropy)
{
long time = System.currentTimeMillis();
//String uniqid = String.format("%fd%05f", Math.floor(time),(time-Math.floor(time))*1000000);
//uniqid = uniqid.substring(0, 13);
String uniqid = "";
if(!more_entropy)
{
uniqid = String.format("%s%08x%05x", prefix, time/1000, time);
}else
{
SecureRandom sec = new SecureRandom();
byte[] sbuf = sec.generateSeed(8);
ByteBuffer bb = ByteBuffer.wrap(sbuf);
uniqid = String.format("%s%08x%05x", prefix, time/1000, time);
uniqid += "." + String.format("%.8s", ""+bb.getLong()*-1);
}
return uniqid ;
}
}
@arekrob
Copy link

arekrob commented Jan 9, 2015

In PHP the prefix and more_entropy parameters are optional (see: http://php.net/manual/en/function.uniqid.php ).

@unobatbayar
Copy link

Entropy is important to ensure more uniqueness. Nicely done!

@ninjachen
Copy link

uniqid() in PHP will return 13 char by default, and the method above will return 19 char in Java

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment