forked from canonical/secboot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpbkdf2.go
107 lines (90 loc) · 2.49 KB
/
pbkdf2.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2024 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package secboot
import (
"crypto"
"errors"
"fmt"
"math"
"time"
"github.com/snapcore/secboot/internal/pbkdf2"
"golang.org/x/xerrors"
)
const (
pbkdf2Type = "pbkdf2"
)
var (
pbkdf2Benchmark = pbkdf2.Benchmark
)
type PBKDF2Options struct {
TargetDuration time.Duration
ForceIterations uint32
HashAlg crypto.Hash
}
func (o *PBKDF2Options) kdfParams(keyLen uint32) (*kdfParams, error) {
if keyLen > math.MaxInt32 {
return nil, errors.New("invalid key length")
}
defaultHashAlg := crypto.SHA256
switch {
case keyLen >= 48 && keyLen < 64:
defaultHashAlg = crypto.SHA384
case keyLen >= 64:
defaultHashAlg = crypto.SHA512
}
switch {
case o.ForceIterations > 0:
// The non-benchmarked path. Ensure that ForceIterations
// fits into an int32 so that it always fits into an int
switch {
case o.ForceIterations > math.MaxInt32:
return nil, fmt.Errorf("invalid iterations count %d", o.ForceIterations)
}
params := &kdfParams{
Type: pbkdf2Type,
Time: int(o.ForceIterations), // no limit to the time cost.
Hash: HashAlg(defaultHashAlg),
}
if o.HashAlg != crypto.Hash(0) {
switch o.HashAlg {
case crypto.SHA1, crypto.SHA224, crypto.SHA256, crypto.SHA384, crypto.SHA512:
params.Hash = HashAlg(o.HashAlg)
default:
return nil, errors.New("invalid hash algorithm")
}
}
return params, nil
default:
targetDuration := 2 * time.Second // the default target duration is 2s.
HashAlg := defaultHashAlg
if o.TargetDuration != 0 {
targetDuration = o.TargetDuration
}
if o.HashAlg != crypto.Hash(0) {
HashAlg = o.HashAlg
}
iterations, err := pbkdf2Benchmark(targetDuration, HashAlg)
if err != nil {
return nil, xerrors.Errorf("cannot benchmark KDF: %w", err)
}
o = &PBKDF2Options{
ForceIterations: uint32(iterations),
HashAlg: HashAlg}
return o.kdfParams(keyLen)
}
}