Created
July 18, 2019 10:51
-
-
Save yukithm/1c4dea9e17af985fa1011cc5960f0b8b to your computer and use it in GitHub Desktop.
[Kotlin] Create secure random token
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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