From d758dbb28c276d2e5bbb7262e0767e2043034806 Mon Sep 17 00:00:00 2001 From: George Shaw Date: Thu, 26 Oct 2017 16:17:27 -0500 Subject: [PATCH] added password hashing and testing for the functions --- pkg/encryption/password.go | 19 +++++++++++++++++ pkg/encryption/password_test.go | 38 +++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 pkg/encryption/password.go create mode 100644 pkg/encryption/password_test.go diff --git a/pkg/encryption/password.go b/pkg/encryption/password.go new file mode 100644 index 0000000..0dcecb3 --- /dev/null +++ b/pkg/encryption/password.go @@ -0,0 +1,19 @@ +// Encryption package has functions inside of it that utilize various encypting and hashing techniques +package encryption + +import "golang.org/x/crypto/bcrypt" + +func HashPassword(password string) (string, error) { + hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + return string(hash), err +} + +func CheckPassword(hash, plainText []byte) (bool, error) { + err := bcrypt.CompareHashAndPassword(hash, plainText) + + if err != nil { + return false, err + } + + return true, nil +} diff --git a/pkg/encryption/password_test.go b/pkg/encryption/password_test.go new file mode 100644 index 0000000..fce1de3 --- /dev/null +++ b/pkg/encryption/password_test.go @@ -0,0 +1,38 @@ +// Encryption package has functions inside of it that utilize various encypting and hashing techniques +package encryption + +import "testing" + +func TestPasswordHashing(t *testing.T) { + passwords := []struct { + ok bool + plainText string + hash string + }{ + {true, "fd#@$s4$oiahfoij", ""}, + {false, "ashf324yiuf!@#", ""}, + {true, "4892fjsk#@(!!)", ""}, + {false, "fsufh$&*(#(*f))", ""}, + } + + for _, password := range passwords { + var err error + if password.ok { + password.hash, err = HashPassword(password.plainText) + } else { + password.hash, err = HashPassword("this will fail") + } + + if err != nil { + t.Errorf("Error in password_test using HashPassword func: %s", err.Error()) + } + + ok, err := CheckPassword([]byte(password.hash), []byte(password.plainText)) + + if err != nil { + if ok != password.ok { + t.Errorf("In password_test expected %t, but got %t from CheckPassword func", password.ok, ok) + } + } + } +}