Random string password generator in Scala

Managing 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.

asked Mar 2, 2014 by Eric Z Ma (43,790 points)
edited Mar 4, 2014 by Eric Z Ma

2 Answers

 
Best answer

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.

answered Mar 2, 2014 by Eric Z Ma (43,790 points)
edited Mar 2, 2014 by Eric Z Ma

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)
  }
}
answered Jan 24 by nunot (140 points)

Please log in or register to answer this question.

Related questions

1 answer
asked Mar 23, 2014 by Eric Z Ma (43,790 points)
1 answer
2 answers
1 answer
1 answer
1 answer
Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...