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 (44,280 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) {

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 (44,280 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, 2017 by nunot (140 points)

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost