Add bcrypt utilities

This commit is contained in:
Luis Eduardo Jeréz Girón
2024-07-20 16:40:04 -06:00
parent b727e71393
commit 9e35994b74
2 changed files with 64 additions and 0 deletions

View 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
}

View 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())
}