如何使用当前时间戳创建随机字符串作为Java中的salt?

时间:2012-07-03 19:20:39

标签: java random timestamp

我想根据当前时间戳创建一个随机字符串(输出到控制台以进行调试)。

例如,控制台将输出:

Setting up browser [123456]...
Getting configuration [758493]...
Completed: [758493].
Completed: [123456].

此处123456758493是我正在尝试生成的随机字符串。

以下是我认为它可以起作用的伪代码:

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;
}

任何人都可以帮助解决这个问题(需要导入什么),和/或可能建议改进吗?

3 个答案:

答案 0 :(得分:6)

这取决于“当前时间戳”的含义。您可以使用System.currentTimeMillis(),但这不一定是唯一 - 如果您在短时间内多次调用它,您可能会多次获得相同的结果。还有System.nanoTime()

作为替代方案,您可以使用UUID.randomUUID(),使用所有位或某个子集。 (如果您决定使用子集,则应仔细选择它们。并非UUID中的所有位都相同。)

答案 1 :(得分:2)

来自System.nanoTime()的MD5怎么样?

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();

4次调用的结果:

bbf9123ac9335581535350e863236800
67fef4376523ae683b2e1d54fd97df53
ef1e747dc916584baed73a0921410216
8c8bc839bf739210a3875966430879de

答案 2 :(得分:-4)

基于当前时间戳的密钥:

npm install random-key-generator