3
0
mirror of https://github.com/ergochat/ergo.git synced 2024-11-14 07:59:31 +01:00
ergo/irc/passwd/salted.go

67 lines
2.1 KiB
Go
Raw Normal View History

2017-03-27 14:15:02 +02:00
// Copyright (c) 2016 Daniel Oaks <daniel@danieloaks.net>
// released under the MIT license
2017-10-05 16:03:53 +02:00
package passwd
import (
"crypto/rand"
"golang.org/x/crypto/bcrypt"
)
2017-10-05 16:03:53 +02:00
const (
// newSaltLen is how many bytes long newly-generated salts are.
newSaltLen = 30
// defaultPasswordCost is the bcrypt cost we use for passwords.
defaultPasswordCost = 14
)
// NewSalt returns a salt for crypto uses.
func NewSalt() ([]byte, error) {
salt := make([]byte, newSaltLen)
_, err := rand.Read(salt)
if err != nil {
var emptySalt []byte
return emptySalt, err
}
return salt, nil
}
2017-10-05 16:03:53 +02:00
// SaltedManager supports the hashing and comparing of passwords with the given salt.
type SaltedManager struct {
salt []byte
}
2017-10-05 16:03:53 +02:00
// NewSaltedManager returns a new SaltedManager with the given salt.
func NewSaltedManager(salt []byte) SaltedManager {
2017-10-07 14:19:37 +02:00
return SaltedManager{
salt: salt,
}
}
// assemblePassword returns an assembled slice of bytes for the given password details.
2017-10-05 16:03:53 +02:00
func (sm *SaltedManager) assemblePassword(specialSalt []byte, password string) []byte {
var assembledPasswordBytes []byte
2017-10-05 16:03:53 +02:00
assembledPasswordBytes = append(assembledPasswordBytes, sm.salt...)
assembledPasswordBytes = append(assembledPasswordBytes, '-')
assembledPasswordBytes = append(assembledPasswordBytes, specialSalt...)
assembledPasswordBytes = append(assembledPasswordBytes, '-')
assembledPasswordBytes = append(assembledPasswordBytes, []byte(password)...)
return assembledPasswordBytes
}
// GenerateFromPassword encrypts the given password.
2017-10-05 16:03:53 +02:00
func (sm *SaltedManager) GenerateFromPassword(specialSalt []byte, password string) ([]byte, error) {
assembledPasswordBytes := sm.assemblePassword(specialSalt, password)
return bcrypt.GenerateFromPassword(assembledPasswordBytes, defaultPasswordCost)
}
// CompareHashAndPassword compares a hashed password with its possible plaintext equivalent.
// Returns nil on success, or an error on failure.
2017-10-05 16:03:53 +02:00
func (sm *SaltedManager) CompareHashAndPassword(hashedPassword []byte, specialSalt []byte, password string) error {
assembledPasswordBytes := sm.assemblePassword(specialSalt, password)
return bcrypt.CompareHashAndPassword(hashedPassword, assembledPasswordBytes)
}