/
key_derivation_nontest.go
67 lines (52 loc) · 1.97 KB
/
key_derivation_nontest.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
//go:build !testing
// +build !testing
package crypto
import (
"fmt"
"github.com/pkg/errors"
)
const (
// MasterKeyLength describes the length of the master key.
MasterKeyLength = 32
)
// DefaultKeyDerivationAlgorithm is the key derivation algorithm for new configurations.
const DefaultKeyDerivationAlgorithm = ScryptAlgorithm
// KeyDeriver is an interface that contains methods for deriving a key from a password.
type KeyDeriver interface {
DeriveKeyFromPassword(password string, salt []byte) ([]byte, error)
RecommendedSaltLength() int
}
//nolint:gochecknoglobals
var keyDerivers = map[string]KeyDeriver{}
// RegisterKeyDerivers registers various key derivation functions.
func RegisterKeyDerivers(name string, keyDeriver KeyDeriver) {
if _, ok := keyDerivers[name]; ok {
panic(fmt.Sprintf("key deriver (%s) is already registered", name))
}
keyDerivers[name] = keyDeriver
}
// DeriveKeyFromPassword derives encryption key using the provided password and per-repository unique ID.
func DeriveKeyFromPassword(password string, salt []byte, algorithm string) ([]byte, error) {
kd, ok := keyDerivers[algorithm]
if !ok {
return nil, errors.Errorf("unsupported key algorithm: %v, supported algorithms %v", algorithm, AllowedKeyDerivationAlgorithms())
}
//nolint:wrapcheck
return kd.DeriveKeyFromPassword(password, salt)
}
// RecommendedSaltLength returns the recommended salt length of a given key derivation algorithm.
func RecommendedSaltLength(algorithm string) (int, error) {
kd, ok := keyDerivers[algorithm]
if !ok {
return 0, errors.Errorf("unsupported key algorithm: %v, supported algorithms %v", algorithm, AllowedKeyDerivationAlgorithms())
}
return kd.RecommendedSaltLength(), nil
}
// AllowedKeyDerivationAlgorithms returns a slice of the allowed key derivation algorithms.
func AllowedKeyDerivationAlgorithms() []string {
kdAlgorithms := make([]string, 0, len(keyDerivers))
for k := range keyDerivers {
kdAlgorithms = append(kdAlgorithms, k)
}
return kdAlgorithms
}