diff options
Diffstat (limited to 'internal/userutil')
-rw-r--r-- | internal/userutil/userutil.go | 16 | ||||
-rw-r--r-- | internal/userutil/userutil_test.go | 76 |
2 files changed, 92 insertions, 0 deletions
diff --git a/internal/userutil/userutil.go b/internal/userutil/userutil.go index d5c74325..8063aef0 100644 --- a/internal/userutil/userutil.go +++ b/internal/userutil/userutil.go @@ -5,6 +5,8 @@ package userutil import ( + "crypto/sha256" + "crypto/subtle" "encoding/hex" "fmt" "image/png" @@ -14,6 +16,7 @@ import ( "strings" "github.com/pkg/errors" + "golang.org/x/crypto/pbkdf2" "gogs.io/gogs/internal/avatar" "gogs.io/gogs/internal/conf" @@ -77,3 +80,16 @@ func GenerateRandomAvatar(userID int64, name, email string) error { } return nil } + +// EncodePassword encodes password using PBKDF2 SHA256 with given salt. +func EncodePassword(password, salt string) string { + newPasswd := pbkdf2.Key([]byte(password), []byte(salt), 10000, 50, sha256.New) + return fmt.Sprintf("%x", newPasswd) +} + +// ValidatePassword returns true if the given password matches the encoded +// version with given salt. +func ValidatePassword(encoded, salt, password string) bool { + got := EncodePassword(password, salt) + return subtle.ConstantTimeCompare([]byte(encoded), []byte(got)) == 1 +} diff --git a/internal/userutil/userutil_test.go b/internal/userutil/userutil_test.go index e90c9235..10ffa12a 100644 --- a/internal/userutil/userutil_test.go +++ b/internal/userutil/userutil_test.go @@ -77,3 +77,79 @@ func TestGenerateRandomAvatar(t *testing.T) { got := osutil.IsFile(CustomAvatarPath(1)) assert.True(t, got) } + +func TestEncodePassword(t *testing.T) { + want := EncodePassword("123456", "rands") + tests := []struct { + name string + password string + rands string + wantEqual bool + }{ + { + name: "correct", + password: "123456", + rands: "rands", + wantEqual: true, + }, + + { + name: "wrong password", + password: "111333", + rands: "rands", + wantEqual: false, + }, + { + name: "wrong salt", + password: "111333", + rands: "salt", + wantEqual: false, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got := EncodePassword(test.password, test.rands) + if test.wantEqual { + assert.Equal(t, want, got) + } else { + assert.NotEqual(t, want, got) + } + }) + } +} + +func TestValidatePassword(t *testing.T) { + want := EncodePassword("123456", "rands") + tests := []struct { + name string + password string + rands string + wantEqual bool + }{ + { + name: "correct", + password: "123456", + rands: "rands", + wantEqual: true, + }, + + { + name: "wrong password", + password: "111333", + rands: "rands", + wantEqual: false, + }, + { + name: "wrong salt", + password: "111333", + rands: "salt", + wantEqual: false, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got := ValidatePassword(want, test.rands, test.password) + assert.Equal(t, test.wantEqual, got) + }) + } +} |