Skip to content

Instantly share code, notes, and snippets.

@Audhil
Created June 11, 2017 18:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Audhil/3e4332e14f0583062ead8147ab185d7b to your computer and use it in GitHub Desktop.
Save Audhil/3e4332e14f0583062ead8147ab185d7b to your computer and use it in GitHub Desktop.
Tip to generate random password in Kotlin
fun generateRandomPassword(): String {
val chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
var passWord = ""
for (i in 0..31) {
passWord += chars[Math.floor(Math.random() * chars.length).toInt()]
}
return passWord
}
@cristan
Copy link

cristan commented Nov 15, 2018

Since Kotlin 1.3 you can use Random.nextInt(0, chars.length) instead of Math.floor(Math.random() * chars.length).toInt().

@christophsturm
Copy link

        private val STRING_CHARACTERS = ('0'..'z').toList().toTypedArray()
        val password = (1..32).map { STRING_CHARACTERS.random() }.joinToString("")

@christophsturm
Copy link

just stumbled over this, I'm not saying that thats how you should ever create a password. just wanted to show a simpler way

@LarsArtmann
Copy link

private val chars = ('a'..'Z') + ('A'..'Z') + ('0'..'9')
private fun randomID(): String = List(16) { chars.random() }.joinToString("")

@lawloretienne
Copy link

private val chars = ('a'..'Z') + ('A'..'Z') + ('0'..'9')
private fun randomID(): String = List(16) { chars.random() }.joinToString("")

This worked for me.

@nancwang
Copy link

// Could be this way for a length of 8 password with visible ascii characters
var password = List(8){(0x21..0x7e).random().toChar()}.joinToString("")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment