Created
December 21, 2023 07:07
-
-
Save jsadeli/42fef8e5e01d5f4ddf15c630a014ffc7 to your computer and use it in GitHub Desktop.
Proof Key for Code Exchange (PKCE) for OAuth 2.0
This file contains hidden or 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
#!/usr/bin/env kotlin | |
import java.security.MessageDigest | |
import java.util.Base64 | |
import kotlin.random.Random | |
/** | |
* Proof Key for Code Exchange (PKCE) for OAuth 2.0 | |
*/ | |
fun pkce() { | |
val secureRandom: ByteArray = Random.nextBytes(32) | |
val verifier: String = secureRandom.toSha256Hash() | |
println("code_verifier: $verifier") | |
val challenge: String = verifier.toSha256Hash() | |
println("code_challenge: $challenge") | |
} | |
// region helper extension methods | |
/** | |
* Returns a `SHA-256` encoded string from an input string. | |
*/ | |
fun String.toSha256Hash(): String { | |
return this.toByteArray().toSha256Hash() | |
} | |
/** | |
* Returns a `SHA-256` encoded string from an input byte array. | |
*/ | |
fun ByteArray.toSha256Hash(): String { | |
val sha256: MessageDigest = MessageDigest.getInstance("SHA-256") | |
val hash: ByteArray = sha256.digest(this) | |
return Base64.getUrlEncoder().withoutPadding().encodeToString(hash) | |
} | |
// endregion | |
pkce() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment