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

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

例如,控制台将输出:

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

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

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

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

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

基于密钥的当前时间戳:

 npm install random-key-generator