0

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

fgonzalez
  • 3,787
  • 7
  • 45
  • 79

4 Answers4

2

You could probably use something like this

import java.util.uuid;
...

UUID  newUUID = UUID.randomUUID();

String.valueOf(newUUID);

...
PKey
  • 3,715
  • 1
  • 14
  • 39
1

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.

Deceiver
  • 324
  • 1
  • 2
  • 12
1

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

Community
  • 1
  • 1
John K
  • 462
  • 2
  • 11
  • `Random` doesn't provide cryptographically secure random bytes. `SecureRandom` should be used instead. – Artjom B. Aug 04 '16 at 17:23
  • He isn't using it for cryptography. he just needs a random UUID. – John K Aug 04 '16 at 17:39
  • The collisions with `Random` might be too high to call the result "unique". Anyway, [`UUID` also uses `SecureRandom` internally](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/UUID.java#UUID). – Artjom B. Aug 04 '16 at 18:58
  • The implementation of nextBytes is doc'd here:https://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextBytes(byte[]) so essentially it's calling nextInt() for each byte. I won't pretend to know enough about cryptography to know how much entropy this generates as opposed to other methods implemented by SecureRandom. That being said, I doubt there will be many collisions with this implementation. – John K Aug 04 '16 at 22:02
0

Try this:

SecureRandom random = new SecureRandom();
new BigInteger(256, random).toString(32);
Sándor Juhos
  • 1,535
  • 1
  • 12
  • 19