snapshot of https://github.com/traggo/server.git (master, 2026-09-16; blobs > 131072B omitted)
Some checks failed
build / build (push) Failing after 3s
Some checks failed
build / build (push) Failing after 3s
This commit is contained in:
17
user/password/password.go
Normal file
17
user/password/password.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package password
|
||||
|
||||
import "golang.org/x/crypto/bcrypt"
|
||||
|
||||
// CreatePassword returns a hashed version of the given password.
|
||||
func CreatePassword(pw string, strength int) []byte {
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(pw), strength)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return hashedPassword
|
||||
}
|
||||
|
||||
// ComparePassword compares a hashed password with its possible plaintext equivalent.
|
||||
func ComparePassword(hashedPassword, password []byte) bool {
|
||||
return bcrypt.CompareHashAndPassword(hashedPassword, password) == nil
|
||||
}
|
||||
21
user/password/password_test.go
Normal file
21
user/password/password_test.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestPasswordSuccess(t *testing.T) {
|
||||
password := CreatePassword("secret", 4)
|
||||
assert.Equal(t, true, ComparePassword(password, []byte("secret")))
|
||||
}
|
||||
|
||||
func TestPasswordFailure(t *testing.T) {
|
||||
password := CreatePassword("secret", 4)
|
||||
assert.Equal(t, false, ComparePassword(password, []byte("secretx")))
|
||||
}
|
||||
|
||||
func TestBCryptFailure(t *testing.T) {
|
||||
assert.Panics(t, func() { CreatePassword("secret", 12312) })
|
||||
}
|
||||
Reference in New Issue
Block a user