From 3c7d5fcee11afa7887132c634ab2e84a4a44224a Mon Sep 17 00:00:00 2001 From: Eng Zer Jun Date: Sun, 23 Jul 2023 17:14:48 +0800 Subject: [PATCH] util: Compare password hashing method with `strings.EqualFold` Comparing two strings to the same case with `strings.ToLower` is more computational expensive than `strings.EqualFold`. Sample benchmark: package auth_test import ( "strings" "testing" ) func BenchmarkToLower(b *testing.B) { for i := 0; i < b.N; i++ { if strings.ToLower("PBKDF2") != strings.ToLower("pbkdf2") { b.Fail() } } } func BenchmarkEqualFold(b *testing.B) { for i := 0; i < b.N; i++ { if !strings.EqualFold("PBKDF2", "pbkdf2") { b.Fail() } } } goos: linux goarch: amd64 pkg: go.thethings.network/lorawan-stack/v3/pkg/auth cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics BenchmarkToLower-16 14323047 98.17 ns/op 8 B/op 1 allocs/op BenchmarkEqualFold-16 132120366 8.705 ns/op 0 B/op 0 allocs/op PASS ok go.thethings.network/lorawan-stack/v3/pkg/auth 3.267s Signed-off-by: Eng Zer Jun --- pkg/auth/password.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/auth/password.go b/pkg/auth/password.go index 8c13f4cae2..1561fab7c1 100644 --- a/pkg/auth/password.go +++ b/pkg/auth/password.go @@ -92,7 +92,7 @@ func Validate(hashed, plain string) (bool, error) { typ := parts[0] for _, method := range hashValidators { - if strings.ToLower(typ) == strings.ToLower(method.Name()) { + if strings.EqualFold(typ, method.Name()) { return method.Validate(hashed, plain) } }