2017-07-12 11:05:18 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import "encoding/base64"
|
|
|
|
import "crypto/rand"
|
|
|
|
import "golang.org/x/crypto/bcrypt"
|
|
|
|
|
|
|
|
// Generate a cryptographically secure set of random bytes..
|
|
|
|
func GenerateSafeString(length int) (string, error) {
|
2017-09-03 04:50:31 +00:00
|
|
|
rb := make([]byte, length)
|
2017-07-12 11:05:18 +00:00
|
|
|
_, err := rand.Read(rb)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return base64.URLEncoding.EncodeToString(rb), nil
|
|
|
|
}
|
|
|
|
|
2017-09-03 04:50:31 +00:00
|
|
|
// Generate a bcrypt hash from a password and a salt
|
|
|
|
func BcryptGeneratePassword(password string) (hashedPassword string, salt string, err error) {
|
2017-07-12 11:05:18 +00:00
|
|
|
salt, err = GenerateSafeString(saltLength)
|
|
|
|
if err != nil {
|
|
|
|
return "", "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
password = password + salt
|
2017-09-03 04:50:31 +00:00
|
|
|
hashedPassword, err = bcryptGeneratePasswordNoSalt(password)
|
2017-07-12 11:05:18 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", "", err
|
|
|
|
}
|
2017-09-03 04:50:31 +00:00
|
|
|
return hashedPassword, salt, nil
|
2017-07-12 11:05:18 +00:00
|
|
|
}
|
|
|
|
|
2017-09-03 04:50:31 +00:00
|
|
|
func bcryptGeneratePasswordNoSalt(password string) (hash string, err error) {
|
|
|
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
2017-07-12 11:05:18 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2017-09-03 04:50:31 +00:00
|
|
|
return string(hashedPassword), nil
|
2017-07-12 11:05:18 +00:00
|
|
|
}
|