简体   繁体   English

用Java生成唯一密钥

[英]Generate unique key in Java

We are migrating a server project coded using NodeJs to one coded in Java. 我们正在将使用NodeJs编码的服务器项目迁移到Java编码的项目。 I'm not very into the cryptography thing but I need to "translate" the following instruction to Java. 我不太喜欢密码学,但是我需要将以下指令“翻译”为Java。

crypto.randomBytes(32).toString('hex');

Basically in the node js project they were using the js library crypto to generate a unique key, and I would need to do the same, no more, no less, in java. 基本上在node js项目中,他们使用js库crypto来生成唯一密钥,而我需要在Java中做同样的事情,不多也不少。 Anyone with crypto knowledge that can help here? 有加密知识的人可以在这里提供帮助吗? What would be the equivalent in Java? 在Java中相当于什么?

Thanks 谢谢

You could probably use something like this 你可能会用这样的东西

import java.util.uuid;
...

UUID  newUUID = UUID.randomUUID();

String.valueOf(newUUID);

...

You can use the UUID from java: 您可以从Java使用UUID:

UUID.randomUUID()

Through a quick search on google I got https://paragonie.com/blog/2016/05/how-generate-secure-random-numbers-in-various-programming-languages , have a look and for your case the closest thing will be: 通过在Google上的快速搜索,我得到了https://paragonie.com/blog/2016/05/how-generate-secure-random-numbers-in-various-programming-languages ,看看一下,对于您的情况最接近将会:

SecureRandom csprng = new SecureRandom();
byte[] randomBytes = new byte[32];
csprng.nextBytes(randombytes);

This is in the blog. 这是在博客中。 Hope it helps. 希望能帮助到你。

You can use 您可以使用

Random.nextBytes(byte[] bytes) 

to populate a random byte array and then convert the bytes to hex using the strategies discussed here 填充随机字节数组,然后使用此处讨论的策略将字节转换为十六进制

Try this: 尝试这个:

SecureRandom random = new SecureRandom();
new BigInteger(256, random).toString(32);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM