package org.kodejava.security;
import java.security.SecureRandom;
import java.util.Random;
public class RandomString {
public static final String SOURCES =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
public static void main(String[] args) {
RandomString rs = new RandomString();
System.out.println(rs.generateString(new Random(), SOURCES, 10));
System.out.println(rs.generateString(new Random(), SOURCES, 10));
System.out.println(rs.generateString(new SecureRandom(), SOURCES, 15));
System.out.println(rs.generateString(new SecureRandom(), SOURCES, 15));
}
/**
* Generate a random string.
*
* @param random the random number generator.
* @param characters the characters for generating string.
* @param length the length of the generated string.
*/
public String generateString(Random random, String characters, int length) {
char[] text = new char[length];
for (int i = 0; i < length; i++) {
text[i] = characters.charAt(random.nextInt(characters.length()));
}
return new String(text);
}
}
Example string produced by the code snippets are:
bJGjSgoy7G
SoeTjBy83s
IolJZtkttJixAVY
ZOvQnICNcwcCdJ8
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024