From 5b59d00f845a85e6a44095e8dbef7ad543f5bdb7 Mon Sep 17 00:00:00 2001 From: zmstone Date: Thu, 23 Oct 2025 11:35:50 +0200 Subject: [PATCH] fix: for nonce avoid base64 padding with '=' '=' is technically not forbidden and it worked just fine with Kafka since day 1, but it could potentially become an issue maybe in the future for some other Kafka API compatible server. --- changelog.md | 3 +++ src/kpro_scram.erl | 15 ++++++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/changelog.md b/changelog.md index f98a397..7072729 100644 --- a/changelog.md +++ b/changelog.md @@ -1,3 +1,6 @@ +* 4.2.10 + - Refactor SCRAM nonce for client first message to pick from char-set `a-zA-Z0-9`. + * 4.2.9 - Improve message encoding performance. - Allow `{magic_v2, Size, IoList}` as batch input for `produce` request. diff --git a/src/kpro_scram.erl b/src/kpro_scram.erl index 25ad709..3ecab12 100644 --- a/src/kpro_scram.erl +++ b/src/kpro_scram.erl @@ -1,5 +1,6 @@ %%% %%% Copyright (c) 2018-2021, Klarna Bank AB (publ) +%%% Copyright (c) 2022-2025, Kafka4beam %%% %%% Licensed under the Apache License, Version 2.0 (the "License"); %%% you may not use this file except in compliance with the License. @@ -41,7 +42,7 @@ %% @doc Initialize a scram context. -spec init(sha256 | sha512, binary(), binary()) -> scram(). init(Sha, User, Pass) -> - Nonce = base64:encode(crypto:strong_rand_bytes(2 * ?MY_NONCE_LEN div 3)), + Nonce = nonce(?MY_NONCE_LEN), #{ sha => Sha , pass => Pass , nonce => Nonce @@ -141,6 +142,18 @@ hmac(Sha, Key, Data) -> crypto:hmac(Sha, Key, Data). -endif. +nonce(Bytes) -> + bin(rand_chars(Bytes)). + +rand_chars(0) -> []; +rand_chars(N) -> [rand_char() | rand_chars(N - 1)]. + +rand_char() -> base62(rand:uniform(62) - 1). + +base62(I) when I < 26 -> $A + I; +base62(I) when I < 52 -> $a + I - 26; +base62(I) -> $0 + I - 52. + %%%_* Emacs ==================================================================== %%% Local Variables: %%% allout-layout: t