Random string password generator in Scala
Posted on In QAManaging our research cluster, I frequently need to generate some string for new users’ password. How to generate them automatically and randomly in Scala? The passwords need characters ‘a’ – ‘z’, ‘A’ – ‘Z’ and ‘0’ – ‘9’ only.
This piece of code works very well for me:
def randomString(len: Int): String = {
val rand = new scala.util.Random(System.nanoTime)
val sb = new StringBuilder(len)
val ab = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
for (i <- 0 until len) {
sb.append(ab(rand.nextInt(ab.length)))
}
sb.toString
}
The characters are selected pseudo randomly selected from the alphabet (ab
). You can add/delete characters to include/exclude them in the passwords.
Since you’re dealing with passwords, you probably want to have a safer generation method. Here’s an example with SecureRandom
taken from here:
object RandomUtil {
private val random = SecureRandom.getInstanceStrong
def alphanumeric(nrChars: Int = 24): String = {
new BigInteger(nrChars * 5, random).toString(32)
}
}