Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a random string with a specific bit size in java

Tags:

java

How do i do that? Can't seems to find a way. Securerandom doesn't seems to allow me to specify bit size anywhere

like image 462
William Avatar asked Mar 18 '11 11:03

William


People also ask

How do you generate a fixed length random string in Java?

Using randomUUID() java. util. UUID is another Java class that can be used to generate a random string. It offers a static randomUUID() method that returns a random alphanumeric string of 32 characters.

How do you write a random string in Java?

Example 1: Java program to generate a random string Next, we have generated a random index number using the nextInt() method of the Random class. Using the random index number, we have generated the random character from the string alphabet. We then used the StringBuilder class to append all the characters together.

How do you generate unique random strings?

There are many ways to generate a random, unique, alphanumeric string in PHP which are given below: Using str_shuffle() Function: The str_shuffle() function is an inbuilt function in PHP and is used to randomly shuffle all the characters of a string passed to the function as a parameter.


2 Answers

If your bit-count can be divded by 8, in other words, you need a full byte-count, you can use

Random random = ThreadLocalRandom.current();
byte[] r = new byte[256]; //Means 2048 bit
random.nextBytes(r);
String s = new String(r)

If you don't like the strange characters, encode the byte-array as base64:

For example, use the Apache Commons Codec and do:

Random random = ThreadLocalRandom.current();
byte[] r = new byte[256]; //Means 2048 bit
random.nextBytes(r);
String s = Base64.encodeBase64String(r);
like image 119
theomega Avatar answered Oct 13 '22 00:10

theomega


Similar to the other answer with a minor detail

Random random = ThreadLocalRandom.current();
byte[] randomBytes = new byte[32];
random.nextBytes(randomBytes);
String encoded = Base64.getUrlEncoder().encodeToString(randomBytes)

Instead of simply using Base64 encoding, which can leave you with a '+' in the out, make sure it doesn't contain any characters which need to be further URL encoded.

like image 23
atomic_ice Avatar answered Oct 13 '22 00:10

atomic_ice