encryption_go/encryption.go
2017-06-23 17:48:56 +09:00

47 lines
836 B
Go

package encryption
import (
"crypto/rand"
"encoding/hex"
"golang.org/x/crypto/scrypt"
"io"
)
const (
PW_SALT_BYTES = 64
PW_HASH_BYTES = 64
)
func Encrypt(pw string) (string, string, error) {
salt := make([]byte, PW_SALT_BYTES)
_, err := io.ReadFull(rand.Reader, salt)
if err != nil {
return "", "", err
}
hash, err := scrypt.Key([]byte(pw), salt, 16384, 8, 1, PW_HASH_BYTES)
if err != nil {
return "", "", err
}
saltStr := hex.EncodeToString(salt)
hashStr := hex.EncodeToString(hash)
return saltStr, hashStr, nil
}
func Check(pw, savedSalt, savedDigest string) bool {
salt, err := hex.DecodeString(savedSalt)
hash, err := scrypt.Key([]byte(pw), salt, 16384, 8, 1, PW_HASH_BYTES)
if err != nil {
return false
}
new := hex.EncodeToString(hash)
if new == savedDigest {
return true
}
return false
}