Created
January 17, 2015 20:31
-
-
Save ymg/0c6e5680aabca60871db to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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