Skip to content

Instantly share code, notes, and snippets.

@corlaez
Last active June 11, 2020 05:05
Show Gist options
  • Save corlaez/c73351af76cc6b36c342170534b29bf6 to your computer and use it in GitHub Desktop.
Save corlaez/c73351af76cc6b36c342170534b29bf6 to your computer and use it in GitHub Desktop.
Secure Random String

Class usage

Just paste it to a project that supports kotlin language and write a package declaration on the top. Done.

Run from console

Requires kscript to run as a script:

sdk install kscript

Run:

kscript RandomStringScript.kts

Java UUID's are not secure enough. This class and script do a better job at generating secure random Strings.

Thanks!

Thanks for allow importing files in kotlin scripts: https://github.com/holgerbrandl/kscript

Thanks to this Java RandomString implementation that served as a solid base to build on: https://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string/41156#41156

import java.util.*
import java.security.SecureRandom
class RandomString(
length: Int = 21,
val random: Random = SecureRandom(),
symbolsString: String = RandomString.alphanum
) {
val buf: CharArray
val symbols: CharArray
init {
buf = CharArray(length)
symbols = symbolsString.toSet().toCharArray()
if (length < 1 || symbolsString.length < 2)
throw IllegalArgumentException()
}
fun nextString(): String {
for (idx in 0 until buf.size)
buf[idx] = symbols[random.nextInt(symbols.size)]
return String(buf)
}
companion object RandomStringStatic {
val upper: String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
val lower: String = upper.toLowerCase(Locale.ROOT)
val digits: String = "0123456789"
val alphanum: String = upper + lower + digits
}
}
//INCLUDE RandomString.kt
System.out.println(RandomString().nextString())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment