diff --git a/internal/util/cryptoutil/bcrypt.go b/internal/util/cryptoutil/bcrypt.go new file mode 100644 index 0000000..903656b --- /dev/null +++ b/internal/util/cryptoutil/bcrypt.go @@ -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 +} diff --git a/internal/util/cryptoutil/bcrypt_test.go b/internal/util/cryptoutil/bcrypt_test.go new file mode 100644 index 0000000..f6de9d0 --- /dev/null +++ b/internal/util/cryptoutil/bcrypt_test.go @@ -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()) +}