Skip to content

Instantly share code, notes, and snippets.

@yukithm
Created July 18, 2019 10:51
Show Gist options
  • Save yukithm/1c4dea9e17af985fa1011cc5960f0b8b to your computer and use it in GitHub Desktop.
Save yukithm/1c4dea9e17af985fa1011cc5960f0b8b to your computer and use it in GitHub Desktop.
[Kotlin] Create secure random token
import java.security.SecureRandom
import java.util.Base64
// Which is better?
val strong = SecureRandom.getInstanceStrong()
val sha1prng = SecureRandom.getInstance("SHA1PRNG")
println(strong.algorithm)
println(sha1prng.algorithm)
fun ByteArray.toHexString() = joinToString("") { "%02x".format(it) }
val bytes = ByteArray(64)
sha1prng.nextBytes(bytes)
println(bytes.toHexString())
val encoder = Base64.getUrlEncoder().withoutPadding()
val token = encoder.encodeToString(bytes)
println(token)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment