How to generate a random string of 20 characters
public String randomString(String chars, int length) {
Random rand = new Random();
StringBuilder buf = new StringBuilder();
for (int i=0; i<length; i++) {
buf.append(chars.charAt(rand.nextInt(chars.length())));
}
return buf.toString();
}
You may use the class java.util.Random with method
char c = (char)(rnd.nextInt(128-32))+32
20x to get Bytes, which you interpret as ASCII. If you're fine with ASCII.
32 is the offset, from where the characters are printable in general.
I'd use this approach:
String randomString(final int length) {
Random r = new Random(); // perhaps make it a class variable so you don't make a new one every time
StringBuilder sb = new StringBuilder();
for(int i = 0; i < length; i++) {
char c = (char)(r.nextInt((int)(Character.MAX_VALUE)));
sb.append(c);
}
return sb.toString();
}
If you want a byte[] you can do this:
byte[] randomByteString(final int length) {
Random r = new Random();
byte[] result = new byte[length];
for(int i = 0; i < length; i++) {
result[i] = r.nextByte();
}
return result;
}
Or you could do this
byte[] randomByteString(final int length) {
Random r = new Random();
StringBuilder sb = new StringBuilder();
for(int i = 0; i < length; i++) {
char c = (char)(r.nextInt((int)(Character.MAX_VALUE)));
sb.append(c);
}
return sb.toString().getBytes();
}
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 byjava.util.Random
andjava.util.concurrent.ThreadLocalRandom
are mathematically predictable.