From 614a995ef11ff319b1fc21a0a2e92f280a25cdce Mon Sep 17 00:00:00 2001 From: Mostafa Rashed <17770919+mrashed-dev@users.noreply.github.com> Date: Thu, 4 Jan 2024 15:19:39 -0500 Subject: [PATCH] convert hashed string to hex before b64 --- src/main/kotlin/com/nylas/resources/Auth.kt | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/main/kotlin/com/nylas/resources/Auth.kt b/src/main/kotlin/com/nylas/resources/Auth.kt index a224b430..27792c4f 100644 --- a/src/main/kotlin/com/nylas/resources/Auth.kt +++ b/src/main/kotlin/com/nylas/resources/Auth.kt @@ -58,8 +58,7 @@ class Auth(private val client: NylasClient) { val urlBuilder = urlAuthBuilder(config) val secret = UUID.randomUUID().toString() - val sha256Digest = MessageDigest.getInstance("SHA-256").digest(secret.toByteArray()) - val secretHash = Base64.getEncoder().encodeToString(sha256Digest) + val secretHash = hashPkceSecret(secret) urlBuilder .addQueryParameter("response_type", "code") @@ -143,6 +142,18 @@ class Auth(private val client: NylasClient) { return client.executePost(path, responseType, queryParams = params) } + /** + * Hash a plain text secret for use in PKCE + * @param secret The plain text secret to hash + * @return The hashed secret with base64 encoding (without padding) + */ + private fun hashPkceSecret(secret: String): String { + val sha256Digest = MessageDigest.getInstance("SHA-256") + sha256Digest.update(secret.toByteArray()) + val hexString = sha256Digest.digest().joinToString(separator = "") { eachByte -> "%02x".format(eachByte) } + return Base64.getEncoder().withoutPadding().encodeToString(hexString.toByteArray()) + } + /** * Underlying function to build the Hosted Authentication URL * @param config The configuration for building the URL