This commit is contained in:
insanity@loafle.com 2017-05-26 18:17:18 +09:00
parent 0f658e598c
commit ec7379a2ec
2 changed files with 13 additions and 8 deletions

View File

@ -8,30 +8,31 @@ import (
const ( const (
PW_SALT_BYTES = 32 PW_SALT_BYTES = 32
PW_HASH_BYTES = 64 PW_HASH_BYTES = 32
) )
func Encrypt(pw string) ([]byte, []byte, error) { func Encrypt(pw string) (string, string, error) {
salt := make([]byte, PW_SALT_BYTES) salt := make([]byte, PW_SALT_BYTES)
_, err := io.ReadFull(rand.Reader, salt) _, err := io.ReadFull(rand.Reader, salt)
if err != nil { if err != nil {
return nil, nil, err return "", "", err
} }
hash, err := scrypt.Key([]byte(pw), salt, 16384, 8, 1, PW_HASH_BYTES) hash, err := scrypt.Key([]byte(pw), salt, 16384, 8, 1, PW_HASH_BYTES)
if err != nil { if err != nil {
return nil, nil, err return "", "", err
} }
return string(salt), string(hash), nil
return salt, hash, nil
} }
func Check(pw, savedSalt, savedDigest string) bool { func Check(pw, savedSalt, savedDigest string) bool {
hash, err := scrypt.Key([]byte(pw), []byte(savedSalt), 16384, 8, 1, PW_HASH_BYTES) hash, err := scrypt.Key([]byte(pw), []byte(savedSalt), 16384, 8, 1, PW_HASH_BYTES)
if err != nil { if err != nil {
return false return false
} }
if string(hash) == savedDigest { if string(hash) == savedDigest {
return true return true
} }

View File

@ -4,12 +4,16 @@ import (
"testing" "testing"
) )
func TestEncrypt(t *testing.T) { func TestEncrypt(t *testing.T) {
salt, hash, err := Encrypt("MyPassword") salt, hash, err := Encrypt("MyPassword")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
t.Logf("salt : %x\n", salt)
t.Logf("hash : %x\n", hash) b:= Check("MyPassword", salt, hash)
t.Log(b)
} }