go-passwd/pkg/unix/unix.go

65 lines
1.1 KiB
Go
Raw Normal View History

2022-12-07 14:19:04 -07:00
package unix
import (
"crypto/md5"
"crypto/subtle"
"fmt"
"github.com/sour-is/go-passwd"
"golang.org/x/crypto/bcrypt"
)
var All = []passwd.Passwder{
&Blowfish{},
&MD5{},
}
type MD5 struct{}
func (p *MD5) Passwd(pass, check []byte) ([]byte, error) {
2022-12-07 14:19:04 -07:00
h := md5.New()
h.Write(pass)
2022-12-07 14:19:04 -07:00
hash := []byte(fmt.Sprintf("$1$%x", h.Sum(nil)))
2022-12-07 14:19:04 -07:00
return hashCheck(hash, check)
}
func (p *MD5) ApplyPasswd(passwd *passwd.Passwd) {
passwd.Register("1", p)
}
type Blowfish struct{}
func (p *Blowfish) Passwd(pass, check []byte) ([]byte, error) {
if check == nil {
b, err := bcrypt.GenerateFromPassword(pass, bcrypt.DefaultCost)
2022-12-07 14:19:04 -07:00
if err != nil {
return nil, err
2022-12-07 14:19:04 -07:00
}
return b, nil
2022-12-07 14:19:04 -07:00
}
err := bcrypt.CompareHashAndPassword(check, pass)
2022-12-07 14:19:04 -07:00
if err != nil {
return nil, err
2022-12-07 14:19:04 -07:00
}
return check, nil
}
func (p *Blowfish) ApplyPasswd(passwd *passwd.Passwd) {
passwd.Register("2a", p)
}
func hashCheck(hash, check []byte) ([]byte, error) {
if check == nil {
2022-12-07 14:19:04 -07:00
return hash, nil
}
if subtle.ConstantTimeCompare(hash, check) == 1 {
2022-12-07 14:19:04 -07:00
return hash, nil
}
return hash, passwd.ErrNoMatch
}