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{}
|
|
|
|
|
2022-12-10 08:58:08 -07:00
|
|
|
func (p *MD5) Passwd(pass, check []byte) ([]byte, error) {
|
2022-12-07 14:19:04 -07:00
|
|
|
h := md5.New()
|
2022-12-10 08:58:08 -07:00
|
|
|
h.Write(pass)
|
2022-12-07 14:19:04 -07:00
|
|
|
|
2022-12-10 08:58:08 -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{}
|
|
|
|
|
2022-12-10 08:58:08 -07:00
|
|
|
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 {
|
2022-12-10 08:58:08 -07:00
|
|
|
return nil, err
|
2022-12-07 14:19:04 -07:00
|
|
|
}
|
2022-12-10 08:58:08 -07:00
|
|
|
return b, nil
|
2022-12-07 14:19:04 -07:00
|
|
|
}
|
|
|
|
|
2022-12-10 08:58:08 -07:00
|
|
|
err := bcrypt.CompareHashAndPassword(check, pass)
|
2022-12-07 14:19:04 -07:00
|
|
|
if err != nil {
|
2022-12-10 08:58:08 -07:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2022-12-10 08:58:08 -07:00
|
|
|
func hashCheck(hash, check []byte) ([]byte, error) {
|
|
|
|
if check == nil {
|
2022-12-07 14:19:04 -07:00
|
|
|
return hash, nil
|
|
|
|
}
|
|
|
|
|
2022-12-10 08:58:08 -07:00
|
|
|
if subtle.ConstantTimeCompare(hash, check) == 1 {
|
2022-12-07 14:19:04 -07:00
|
|
|
return hash, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return hash, passwd.ErrNoMatch
|
|
|
|
}
|