How to create a random String using the current ti

2019-04-17 03:40发布

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?

3条回答
Anthone
2楼-- · 2019-04-17 03:55

Key-based on current timestamp:

npm install random-key-generator 
查看更多
ゆ 、 Hurt°
3楼-- · 2019-04-17 03:58

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.)

查看更多
你好瞎i
4楼-- · 2019-04-17 04:00

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
查看更多
登录 后发表回答