Generate a pseudo-random password of specific length in Kotlin
This article explores different ways to generate a pseudorandom password of specified length using the specified character set in Kotlin.
Kotlin does not provide any standard function to generate a random password. However, you can randomly choose characters from the provided character set and construct a random string of the desired length out of it.
Consider the following Kotlin program, which can generate an alphanumeric random password of the specified length. The alphanumeric range consists of digits, lowercase, and uppercase characters. In each iteration of the loop, the code randomly chooses a character from the given character set and append it to the StringBuilder instance.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import kotlin.random.Random fun getRandPassword(n: Int): String { val characterSet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" val random = Random(System.nanoTime()) val password = StringBuilder() for (i in 0 until n) { val rIndex = random.nextInt(characterSet.length) password.append(characterSet[rIndex]) } return password.toString() } fun main() { val n = 8 println(getRandPassword(n)) // UFJr7thw } |
That’s all about generating a pseudo-random password of specified length in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)