Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a random string of 20 characters [duplicate]

Tags:

java

Possible Duplicate:
How to generate a random String in Java

I am wanting to generate a random string of 20 characters without using apache classes. I don't really care about whether is alphanumeric or not. Also, I am going to convert it to an array of bytes later FYI.

Thanks,

like image 359
novicePrgrmr Avatar asked Apr 15 '11 23:04

novicePrgrmr


People also ask

How do you generate random strings?

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. If we want to change the random string into lower case, we can use the toLowerCase() method of the String .

How do you generate a random string of characters 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.


1 Answers

Here you go. Just specify the chars you want to allow on the first line.

char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray(); StringBuilder sb = new StringBuilder(20); Random random = new Random(); for (int i = 0; i < 20; i++) {     char c = chars[random.nextInt(chars.length)];     sb.append(c); } String output = sb.toString(); System.out.println(output); 

If you are using this to generate something sensitive like a password reset URL or session ID cookie or temporary password reset, be sure to use java.security.SecureRandom instead. Values produced by java.util.Random and java.util.concurrent.ThreadLocalRandom are mathematically predictable.

like image 173
WhiteFang34 Avatar answered Oct 20 '22 01:10

WhiteFang34