forked from ribice/gorsk
/
secure.go
46 lines (38 loc) · 1.21 KB
/
secure.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package secure
import (
"fmt"
"hash"
"strconv"
"time"
zxcvbn "github.com/nbutton23/zxcvbn-go"
"golang.org/x/crypto/bcrypt"
)
// New initalizes security service
func New(minPWStr int, h hash.Hash) *Service {
return &Service{minPWStr: minPWStr, h: h}
}
// Service holds security related methods
type Service struct {
minPWStr int
h hash.Hash
}
// Password checks whether password is secure enough using zxcvbn library
func (s *Service) Password(pass string, inputs ...string) bool {
pwStrength := zxcvbn.PasswordStrength(pass, inputs)
return pwStrength.Score >= s.minPWStr
}
// Hash hashes the password using bcrypt
func (*Service) Hash(password string) string {
hashedPW, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
return string(hashedPW)
}
// HashMatchesPassword matches hash with password. Returns true if hash and password match.
func (*Service) HashMatchesPassword(hash, password string) bool {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
}
// Token generates new unique token
func (s *Service) Token(str string) string {
s.h.Reset()
fmt.Fprintf(s.h, "%s%s", str, strconv.Itoa(time.Now().Nanosecond()))
return fmt.Sprintf("%x", s.h.Sum(nil))
}