Skip to content

Instantly share code, notes, and snippets.

@PanosJee
Last active December 14, 2015 23:59
Show Gist options
  • Save PanosJee/5170020 to your computer and use it in GitHub Desktop.
Save PanosJee/5170020 to your computer and use it in GitHub Desktop.
Generate Entropy UID for Android
private static String generateUid() {
// STEP 1: get time since Epoch.
// OUTPUT: timestamp in millisecond (or finer) granularity.
// RATIONALE: collision only when app is deployed at the exact same time.
final String s1 = Long.valueOf((new Date()).getTime()).toString();
// STEP 2: get an object reference.
// OUTPUT: memory address or another distinguishable object property.
// RATIONALE: very little probability for two runs to get the
// same address (debatable when in a sandbox).
final String s2 = (new Object()).toString();
// STEP 3: sleep for a little time.
// OUTPUT: time delta in _finer_ millisecond granularity.
// RATIONALE: os fine timing granularity is not guaranteed
// (debatable when dealing with real-time/hard real-time kernels).
final long dat1 = System.nanoTime();
try {
Thread.sleep(256, 42);
} catch (InterruptedException e) {
}
final long dat2 = System.nanoTime();
final String s3 = Long.valueOf(dat2 - dat1).toString();
// STEP 4: generate a random number.
// OUTPUT: random integer.
// RATIONALE: the pseudo-random generator may be the same, but there
// is a slight chance that something might have changed in the
// seed (may be a second passed in some cases).
// Also, some systems (e.g. a JVM) have their own pseudo-random
// generators that are "fed" with their own implementations,
// narrowing the probability for same results.
final String s4 = Integer.valueOf((int) (new Random(System.currentTimeMillis()).nextDouble() * 65535)).toString();
final String s5 = Secure.ANDROID_ID;
// The output string.
final String sall = s1 + s2 + s3 + s4 + s5;
// MD5 from output string.
byte[] thedigest = null;
try {
final byte[] bytesOfMessage = sall.getBytes("UTF-8");
final MessageDigest md = MessageDigest.getInstance("MD5");
thedigest = md.digest(bytesOfMessage);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// RESULT.
return new String(encodeHex(thedigest));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment