简体   繁体   中英

Generate unique key in Java

We are migrating a server project coded using NodeJs to one coded in Java. I'm not very into the cryptography thing but I need to "translate" the following instruction to 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. Anyone with crypto knowledge that can help here? What would be the equivalent in 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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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