From ce3830f6a0583944477fff36bc2c2c41213e1434 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miroslav=20=C5=A0ediv=C3=BD?= Date: Wed, 14 Feb 2024 21:45:04 +0100 Subject: [PATCH] fix: base64 password hash in file members provider to avoid json issues. --- internal/member/file/provider.go | 4 ++- internal/member/file/provider_test.go | 48 +++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 internal/member/file/provider_test.go diff --git a/internal/member/file/provider.go b/internal/member/file/provider.go index ed5c1e7..a7a95c6 100644 --- a/internal/member/file/provider.go +++ b/internal/member/file/provider.go @@ -2,6 +2,7 @@ package file import ( "crypto/sha256" + "encoding/base64" "encoding/json" "io" "os" @@ -27,7 +28,8 @@ func (provider *MemberProviderCtx) hash(password string) string { sha256 := sha256.New() sha256.Write([]byte(password)) - return string(sha256.Sum(nil)) + hashedPassword := sha256.Sum(nil) + return base64.StdEncoding.EncodeToString(hashedPassword) } func (provider *MemberProviderCtx) Connect() error { diff --git a/internal/member/file/provider_test.go b/internal/member/file/provider_test.go new file mode 100644 index 0000000..7e25439 --- /dev/null +++ b/internal/member/file/provider_test.go @@ -0,0 +1,48 @@ +package file + +import ( + "encoding/json" + "testing" + + "github.com/demodesk/neko/pkg/utils" +) + +// Ensure that hashes are the same after encoding and decoding using json +func TestMemberProviderCtx_hash(t *testing.T) { + provider := &MemberProviderCtx{ + config: Config{ + Hash: true, + }, + } + + // generate random strings + passwords := []string{} + for i := 0; i < 10; i++ { + password, err := utils.NewUID(32) + if err != nil { + t.Errorf("utils.NewUID() returned error: %s", err) + } + passwords = append(passwords, password) + } + + for _, password := range passwords { + hashedPassword := provider.hash(password) + + // json encode password hash + hashedPasswordJSON, err := json.Marshal(hashedPassword) + if err != nil { + t.Errorf("json.Marshal() returned error: %s", err) + } + + // json decode password hash json + var hashedPasswordStr string + err = json.Unmarshal(hashedPasswordJSON, &hashedPasswordStr) + if err != nil { + t.Errorf("json.Unmarshal() returned error: %s", err) + } + + if hashedPasswordStr != hashedPassword { + t.Errorf("hashedPasswordStr: %s != hashedPassword: %s", hashedPasswordStr, hashedPassword) + } + } +}