I would like to create a random string (to output to the console for debugging purposes) based off of the current timestamp.
For example, the console would output:
Setting up browser [123456]...
Getting configuration [758493]...
Completed: [758493].
Completed: [123456].
Here the 123456
and 758493
are the random strings I'm trying to generate.
Here's the pseudocode for how I think it can work:
private String random(int len){
long ts = getCurrentTimestamp;
String value = createRandom(len, ts);
//len is the length of the randomString
//and ts is the salt
return value;
}
Can anyone help with the details of this (what needs to be imported), and/or possibly suggest improvements to this?
Well it depends on what you mean by "current timestamp". You could use System.currentTimeMillis()
, but that won't necessarily be unique - if you call it several times in a short period, you may well get the same results several times. There's also System.nanoTime()
.
As an alternative, you could use UUID.randomUUID()
, either using all the bits or some subset. (If you decide to use a subset, you should choose them carefully. Not all bits in a UUID are equal.)
How about MD5 from the System.nanoTime()
?
MessageDigest instance = MessageDigest.getInstance("MD5");
byte[] messageDigest = instance.digest(String.valueOf(System.nanoTime()).getBytes());
StringBuilder hexString = new StringBuilder();
for (int i = 0; i < messageDigest.length; i++) {
String hex = Integer.toHexString(0xFF & messageDigest[i]);
if (hex.length() == 1) {
// could use a for loop, but we're only dealing with a single
// byte
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
Result for 4 invocations:
bbf9123ac9335581535350e863236800
67fef4376523ae683b2e1d54fd97df53
ef1e747dc916584baed73a0921410216
8c8bc839bf739210a3875966430879de
Key-based on current timestamp:
npm install random-key-generator