Reputation: 3877
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
Upvotes: 0
Views: 1596
Reputation: 1615
Try this:
SecureRandom random = new SecureRandom();
new BigInteger(256, random).toString(32);
Upvotes: 0
Reputation: 462
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
Upvotes: 1
Reputation: 324
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.
Upvotes: 1
Reputation: 3841
You could probably use something like this
import java.util.uuid;
...
UUID newUUID = UUID.randomUUID();
String.valueOf(newUUID);
...
Upvotes: 2