1

If java has a function similar to the function in python called urandom from the random library how can I use it?

Python you would do:

import random

random._urandom(1)

What can I do in java for this?

Urandom doesn't generate a random numbers, it returns n random bytes suitable for cryptographic use

Phantom Fangs
  • 57
  • 2
  • 8
  • Can't be. Urandom doesn't generate an integer – Phantom Fangs Jun 02 '19 at 19:31
  • 1
    Look at all methods in [`Random`](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html) class it not only generates integers. Also take a look at [`SecureRandom`](https://docs.oracle.com/javase/8/docs/api/java/security/SecureRandom.html). – Samuel Philipp Jun 02 '19 at 19:33
  • @SamuelPhilipp that would only be a dupe if the methods also use peripheral data as a source of randomness – roganjosh Jun 02 '19 at 19:34
  • 1
    In Python the `random` module is not suitable for cryptographic needs, use the [secrets module](https://docs.python.org/3/library/secrets.html) from Python 3.6 on. – Klaus D. Jun 02 '19 at 19:37
  • @PhantomFangs, `urandom` is *not* "suitable for cryptographic use" (except maybe session keys where they won't last very long); `/dev/urandom`, which it uses (or at least originally used), is explicitly faster but weaker than `/dev/random`, which blocks if there isn't enough entropy to give good values and is thus a far better choice for key generation. – Charles Duffy Jun 02 '19 at 20:01
  • Okay, well, that's python... I asked what to do in java – Phantom Fangs Jun 02 '19 at 20:02
  • Sure, but it influences our understanding of what it actually *is* that you want to do in Java. If you say "I want something like X", it helps if we know which aspects of X you actually care about, and which aspects are incidental (or even misunderstood). – Charles Duffy Jun 02 '19 at 20:03
  • This is very true – Phantom Fangs Jun 02 '19 at 20:03
  • ...if what you really want is to generate random *bytes* in Java, that question doesn't need to refer to Python or urandom at all. – Charles Duffy Jun 02 '19 at 20:05
  • It does considering I felt the need to show an example – Phantom Fangs Jun 02 '19 at 20:19

1 Answers1

4

Use:

byte[] bytes = new byte[x];
new Random().nextBytes(bytes);

Your array will then be filled with random bytes

VoroX
  • 237
  • 1
  • 11