/
format.go
47 lines (40 loc) · 1016 Bytes
/
format.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
47
package password
import (
"bytes"
"errors"
)
type passwordFormat interface {
// ID returns the identifier of the format.
ID() string
// Hash turns the plain password into a hash.
Hash(password []byte) ([]byte, error)
// Compare checks if password is the same as the hash.
Compare(password, hash []byte) error
// CheckHash checks if hash is a valid hash. It is useful when importing an external password hash.
CheckHash(hash []byte) error
}
var errInvalidPasswordFormat = errors.New("invalid password format")
func parsePasswordFormat(h []byte) (id []byte, data []byte, err error) {
i := bytes.IndexByte(h, '$')
if i != 0 {
err = errInvalidPasswordFormat
return
}
h = h[i+1:]
i = bytes.IndexByte(h, '$')
if i == -1 {
err = errInvalidPasswordFormat
return
}
id = h[:i]
data = h[i+1:]
return
}
func constructPasswordFormat(id []byte, data []byte) []byte {
h := make([]byte, len(id)+len(data)+2)
h[0] = '$'
copy(h[1:], id)
h[len(id)+1] = '$'
copy(h[len(id)+2:], data)
return h
}