From 205423775733151d26652fc344dad34b7376287c Mon Sep 17 00:00:00 2001 From: Matt Baer Date: Wed, 29 Jul 2015 17:40:41 -0400 Subject: [PATCH] Add user authentication helpers --- auth/pass.go | 21 +++++++++++++++++++++ auth/pass_test.go | 21 +++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 auth/pass.go create mode 100644 auth/pass_test.go diff --git a/auth/pass.go b/auth/pass.go new file mode 100644 index 0000000..3f771cb --- /dev/null +++ b/auth/pass.go @@ -0,0 +1,21 @@ +package auth + +import "golang.org/x/crypto/bcrypt" + +func clear(b []byte) { + for i := 0; i < len(b); i++ { + b[i] = 0 + } +} + +func HashPass(password []byte) ([]byte, error) { + // Clear memory where plaintext password was stored. + // http://stackoverflow.com/questions/18545676/golang-app-engine-securely-hashing-a-users-password#comment36585613_19828153 + defer clear(password) + // Return hash + return bcrypt.GenerateFromPassword(password, 12) +} + +func Authenticated(hash, pass []byte) bool { + return bcrypt.CompareHashAndPassword(hash, pass) == nil +} diff --git a/auth/pass_test.go b/auth/pass_test.go new file mode 100644 index 0000000..ffadd6e --- /dev/null +++ b/auth/pass_test.go @@ -0,0 +1,21 @@ +package auth + +import "testing" + +const pass = "password" + +var hash []byte + +func TestHash(t *testing.T) { + var err error + hash, err = HashPass([]byte(pass)) + if err != nil { + t.Error("Password hash failed.") + } +} + +func TestAuth(t *testing.T) { + if !Authenticated(hash, []byte(pass)) { + t.Error("Didn't authenticate.") + } +}