2016-06-15 13:50:56 +02:00
|
|
|
// Copyright (c) 2012-2014 Jeremy Latt
|
|
|
|
// released under the MIT license
|
|
|
|
|
2017-10-05 16:03:53 +02:00
|
|
|
package passwd
|
2014-03-02 00:10:04 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/base64"
|
|
|
|
"errors"
|
2016-06-15 13:50:56 +02:00
|
|
|
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
2014-03-02 00:10:04 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2016-10-13 09:36:44 +02:00
|
|
|
// ErrEmptyPassword means that an empty password was given.
|
|
|
|
ErrEmptyPassword = errors.New("empty password")
|
2014-03-02 00:10:04 +01:00
|
|
|
)
|
|
|
|
|
2016-10-13 09:36:44 +02:00
|
|
|
// GenerateEncodedPassword returns an encrypted password, encoded into a string with base64.
|
2014-03-02 00:10:04 +01:00
|
|
|
func GenerateEncodedPassword(passwd string) (encoded string, err error) {
|
|
|
|
if passwd == "" {
|
2016-10-13 09:36:44 +02:00
|
|
|
err = ErrEmptyPassword
|
2014-03-02 00:10:04 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
bcrypted, err := bcrypt.GenerateFromPassword([]byte(passwd), bcrypt.MinCost)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
encoded = base64.StdEncoding.EncodeToString(bcrypted)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-10-13 09:36:44 +02:00
|
|
|
// DecodePasswordHash takes a base64-encoded password hash and returns the appropriate bytes.
|
|
|
|
func DecodePasswordHash(encoded string) (decoded []byte, err error) {
|
2014-03-02 00:10:04 +01:00
|
|
|
if encoded == "" {
|
2016-10-13 09:36:44 +02:00
|
|
|
err = ErrEmptyPassword
|
2014-03-02 00:10:04 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
decoded, err = base64.StdEncoding.DecodeString(encoded)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-10-13 09:36:44 +02:00
|
|
|
// ComparePassword compares a given password with the given hash.
|
2014-03-02 00:10:04 +01:00
|
|
|
func ComparePassword(hash, password []byte) error {
|
|
|
|
return bcrypt.CompareHashAndPassword(hash, password)
|
|
|
|
}
|
2017-10-15 08:18:14 +02:00
|
|
|
|
|
|
|
// ComparePasswordString compares a given password string with the given hash.
|
|
|
|
func ComparePasswordString(hash []byte, password string) error {
|
|
|
|
return ComparePassword(hash, []byte(password))
|
|
|
|
}
|