Skip to content

Instantly share code, notes, and snippets.

@ymg

ymg/hasher.go

Created Jan 17, 2015
Embed
What would you like to do?
/*
password hasher, follows the Mozilla security guide.
blog: https://blog.mozilla.org/webdev/2012/06/08/lets-talk-about-password-storage/
full guide: https://wiki.mozilla.org/WebAppSec/Secure_Coding_Guidelines#Password_Storage
*/
package main
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha512"
"errors"
"golang.org/x/crypto/bcrypt"
"io"
)
const (
KEYLENGTH = 32
)
var ErrGeneratingSalt = errors.New("error generating salt")
var ErrGeneratingBcrypt = errors.New("error generating bcrypt hash")
type Hasher struct{}
func (h *Hasher) NewHash(password string) (string, string, error) {
b := make([]byte, KEYLENGTH)
_, err := io.ReadFull(rand.Reader, b)
if err != nil {
return "", "", ErrGeneratingSalt
}
secret := []byte(password)
salt := b
hmh := hmac.New(sha512.New, salt)
hmh.Write(secret)
hmac_hash := hmh.Sum(nil)
hmh.Reset()
p, err := bcrypt.GenerateFromPassword(hmac_hash, 16)
if err != nil {
return "", "", ErrGeneratingBcrypt
}
return string(p), string(salt), nil
}
func (h *Hasher) CompareHash(hashed_password string, salt string, password string) error {
secret := []byte(password)
s := []byte(salt)
hmh := hmac.New(sha512.New, s)
hmh.Write(secret)
hmac_password := hmh.Sum(nil)
hmh.Reset()
return bcrypt.CompareHashAndPassword([]byte(hashed_password), hmac_password)
}
package main
import "testing"
//testing hashing and validation functions
func TestHasher(t *testing.T) {
secret := "hard password!"
hashing := &Hasher{}
p, s, err := hashing.NewHash(secret)
if err != nil {
t.Error("failed generating hash")
t.Fail()
}
compare_err := hashing.CompareHash(p, s, secret)
if compare_err != nil {
t.Error("failed comparing hashes")
t.Fail()
}
compare_err2 := hashing.CompareHash(p, s, "should fail!")
if compare_err2 == nil {
t.Error("authenticated wrong passwords")
t.Fail()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment