mirror of
https://github.com/eduardolat/pgbackweb.git
synced 2026-02-18 03:18:27 -06:00
Add bcrypt utilities
This commit is contained in:
25
internal/util/cryptoutil/bcrypt.go
Normal file
25
internal/util/cryptoutil/bcrypt.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package cryptoutil
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// CreateHash creates a bcrypt hash of the given password
|
||||
func CreateHash(password string) (string, error) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(hash), nil
|
||||
}
|
||||
|
||||
// VerifyHash verifies the given password against the bcrypt hash
|
||||
func VerifyHash(password, hash string) error {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid password")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
39
internal/util/cryptoutil/bcrypt_test.go
Normal file
39
internal/util/cryptoutil/bcrypt_test.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package cryptoutil
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestCreateHash(t *testing.T) {
|
||||
password := "mysecretpassword"
|
||||
|
||||
hash, err := CreateHash(password)
|
||||
assert.NoError(t, err)
|
||||
assert.NotEmpty(t, hash)
|
||||
}
|
||||
|
||||
func TestVerifyHash(t *testing.T) {
|
||||
password := "mysecretpassword"
|
||||
|
||||
hash, err := CreateHash(password)
|
||||
assert.NoError(t, err)
|
||||
assert.NotEmpty(t, hash)
|
||||
|
||||
err = VerifyHash(password, hash)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestVerifyHash_InvalidPassword(t *testing.T) {
|
||||
password := "mysecretpassword"
|
||||
invalidPassword := "invalidpassword"
|
||||
|
||||
hash, err := CreateHash(password)
|
||||
assert.NoError(t, err)
|
||||
assert.NotEmpty(t, hash)
|
||||
|
||||
err = VerifyHash(invalidPassword, hash)
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, "invalid password", err.Error())
|
||||
}
|
||||
Reference in New Issue
Block a user