-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpassword.go
More file actions
65 lines (51 loc) · 1.46 KB
/
password.go
File metadata and controls
65 lines (51 loc) · 1.46 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package pwdhash
import (
"fmt"
"github.com/allisson/go-pwdhash/internal/encoding"
)
// PasswordHasher manages password hashing operations via registered algorithms.
type PasswordHasher struct {
current Hasher
registry map[string]Hasher
}
// New constructs a PasswordHasher configured via the provided options.
func New(opts ...Option) (*PasswordHasher, error) {
cfg := defaultConfig()
for _, opt := range opts {
opt(cfg)
}
reg := make(map[string]Hasher)
reg[cfg.current.ID()] = cfg.current
return &PasswordHasher{
current: cfg.current,
registry: reg,
}, nil
}
// Hash encodes the provided password using the active hasher.
func (p *PasswordHasher) Hash(password []byte) (string, error) {
return p.current.Hash(password)
}
// Verify checks whether the encoded hash matches the provided password.
func (p *PasswordHasher) Verify(password []byte, encoded string) (bool, error) {
parsed, err := encoding.Parse(encoded)
if err != nil {
return false, err
}
hasher, ok := p.registry[parsed.Algorithm]
if !ok {
return false, fmt.Errorf("unknown hash algorithm: %s", parsed.Algorithm)
}
return hasher.Verify(password, encoded)
}
// NeedsRehash reports whether the encoded hash should be regenerated.
func (p *PasswordHasher) NeedsRehash(encoded string) (bool, error) {
parsed, err := encoding.Parse(encoded)
if err != nil {
return false, err
}
hasher, ok := p.registry[parsed.Algorithm]
if !ok {
return true, nil
}
return hasher.NeedsRehash(encoded)
}