/
scrypt.go
67 lines (58 loc) · 1.1 KB
/
scrypt.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package scrypt
import (
"encoding/hex"
"golang.org/x/crypto/scrypt"
)
const (
// see: https://godoc.org/golang.org/x/crypto/scrypt
defaultCost = 32768
defaultBlockSize = 8
defaultParallelism = 1
defaultKeyLength = 32
)
// SCrypt is struct to create hash.
type SCrypt struct {
Cost int // N
BlockSize int // r
Parallelism int // p
KeyLength int
}
// Hash creates hased text from password.
func (s SCrypt) Hash(password, salt string) string {
hash, err := scrypt.Key(
[]byte(password),
[]byte(salt),
s.getCost(),
s.getBlockSize(),
s.getParallelism(),
s.getKeyLength(),
)
if err != nil {
return ""
}
return hex.EncodeToString(hash)
}
func (s SCrypt) getCost() int {
if s.Cost == 0 {
return defaultCost
}
return s.Cost
}
func (s SCrypt) getBlockSize() int {
if s.BlockSize == 0 {
return defaultBlockSize
}
return s.BlockSize
}
func (s SCrypt) getParallelism() int {
if s.Parallelism == 0 {
return defaultParallelism
}
return s.Parallelism
}
func (s SCrypt) getKeyLength() int {
if s.KeyLength == 0 {
return defaultKeyLength
}
return s.KeyLength
}