How to Generate Random Password in Scala

Generate Random Password in Scala

In this example, we will show simple program snippet about, How to generate random password in scala. The example code were tested and shared in the post.

Example Code

import java.io.File;
import java.io.FileReader;

object PasswordGenetor {
	
	def generatePassword(length: Int): String = {
		
		var values = Array('1', 'A', 'a', 'B', 'b', 'C', 'c', '2', 'D', 'd', 'E', 'e', 'F', 'f', '3', 'G', 'g', 'H', 'h', 'I', 'i', 'J', 'j', 'K', 'k', 'L', 'l', '4', 'M', 'm', 'N', 'n', 'O', 'o', '5', 'P', 'p', 'Q', 'q', 'R', 'r', 'S', 's', 'T', 't', '6', '7', 'U', 'u', 'V', 'v', 'U', 'u', 'W', 'w', '8', 'X', 'x', 'Y', 'y', 'Z', 'z', '9');
		
		var minLen = 5; // Minimum Length
		var maxLen = 15;// Maximum Length
 
		var sb = new StringBuffer();
 
		if (length >= minLen && length <= maxLen) {
			
			var random = 0;
			
			for( i <- 1 to length) {
				// Getting Random Number with in range(ie: 50 total character present)
				random = (Math.random() * (values.length - 1)).toInt;
				sb.append(values(random)); // Appending the character using StringBuffer
			}
		}
		
		return sb.toString;
	}
	

	def main(args: Array[String]) {
	
		println("Generated Password is \""+generatePassword(5)+"\" and length is 5");
		println("Generated Password is \""+generatePassword(6)+"\" and length is 6");
		println("Generated Password is \""+generatePassword(8)+"\" and length is 8");
		println("Generated Password is \""+generatePassword(10)+"\" and length is 10");
		println("Generated Password is \""+generatePassword(12)+"\" and length is 12");
		println("Generated Password is \""+generatePassword(15)+"\" and length is 15");
	}
}

Output

Generated Password is “Wm7Tu” and length is 5
Generated Password is “ZgMICw” and length is 6
Generated Password is “GW7b25TR” and length is 8
Generated Password is “XAIDE6vfCY” and length is 10
Generated Password is “uINNkUmkq1bF” and length is 12
Generated Password is “cKgXy2Ou3x4Hlji” and length is 15

References

1. Generating Password using Java

Hello, folks, I am a founder of dineshkrish.com. I love Java and Open source technologies, If you find my tutorials are useful, please consider making donations to these charities.