gosora/install/utils.go

39 lines
1001 B
Go
Raw Normal View History

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) {
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
}
// 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
hashedPassword, err = bcryptGeneratePasswordNoSalt(password)
2017-07-12 11:05:18 +00:00
if err != nil {
return "", "", err
}
return hashedPassword, salt, nil
2017-07-12 11:05:18 +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
}
return string(hashedPassword), nil
2017-07-12 11:05:18 +00:00
}