Here is a Java 8 solution based on streams.
public String generateString(String alphabet, int length) {
return generateString(alphabet, length, new SecureRandom()::nextInt);
}
// nextInt = bound -> n in [0, bound)
public String generateString(String source, int length, IntFunction<Integer> nextInt) {
StringBuilder sb = new StringBuilder();
IntStream.generate(source::length)
.boxed()
.limit(length)
.map(nextInt::apply)
.map(source::charAt)
.forEach(sb::append);
return sb.toString();
}
Use it like
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int length = 12;
String generated = generateString(alphabet, length);
System.out.println(generated);
The function nextInt should accept an int bound and return a random number between 0 and bound - 1.