-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathhkdf.go
348 lines (311 loc) · 9.01 KB
/
hkdf.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
//go:build !cmd_go_bootstrap
package openssl
import "C"
import (
"errors"
"hash"
"io"
"runtime"
"sync"
"unsafe"
"github.com/golang-fips/openssl/v2/internal/ossl"
)
// SupprtHKDF reports whether the current OpenSSL version supports HKDF.
func SupportsHKDF() bool {
switch vMajor {
case 1:
return versionAtOrAbove(1, 1, 1)
case 3:
_, err := fetchHKDF3()
return err == nil
default:
panic(errUnsupportedVersion())
}
}
func newHKDFCtx1(md ossl.EVP_MD_PTR, mode int32, secret, salt, pseudorandomKey, info []byte) (ctx ossl.EVP_PKEY_CTX_PTR, err error) {
checkMajorVersion(1)
ctx, err = ossl.EVP_PKEY_CTX_new_id(ossl.EVP_PKEY_HKDF, nil)
if err != nil {
return nil, err
}
defer func() {
if err != nil {
ossl.EVP_PKEY_CTX_free(ctx)
}
}()
if _, err := ossl.EVP_PKEY_derive_init(ctx); err != nil {
return ctx, err
}
ctrlSlice := func(ctrl int32, data []byte) bool {
if err != nil {
return false
}
if len(data) == 0 {
return true // No data to set.
}
_, err = ossl.EVP_PKEY_CTX_ctrl(ctx, -1, ossl.EVP_PKEY_OP_DERIVE, ctrl, int32(len(data)), unsafe.Pointer(base(data)))
return err == nil
}
if _, err := ossl.EVP_PKEY_CTX_ctrl(ctx, -1, ossl.EVP_PKEY_OP_DERIVE, ossl.EVP_PKEY_CTRL_HKDF_MODE, mode, nil); err != nil {
return ctx, err
}
if _, err := ossl.EVP_PKEY_CTX_ctrl(ctx, -1, ossl.EVP_PKEY_OP_DERIVE, ossl.EVP_PKEY_CTRL_HKDF_MD, 0, unsafe.Pointer(md)); err != nil {
return ctx, err
}
if ctrlSlice(ossl.EVP_PKEY_CTRL_HKDF_KEY, secret) &&
ctrlSlice(ossl.EVP_PKEY_CTRL_HKDF_SALT, salt) &&
ctrlSlice(ossl.EVP_PKEY_CTRL_HKDF_KEY, pseudorandomKey) &&
ctrlSlice(ossl.EVP_PKEY_CTRL_HKDF_INFO, info) {
return ctx, err
}
return ctx, nil
}
type hkdf1 struct {
ctx ossl.EVP_PKEY_CTX_PTR
hashLen int
buf []byte
}
func (c *hkdf1) finalize() {
if c.ctx != nil {
ossl.EVP_PKEY_CTX_free(c.ctx)
}
}
func (c *hkdf1) Read(p []byte) (int, error) {
defer runtime.KeepAlive(c)
// EVP_PKEY_derive doesn't support incremental output, each call
// derives the key from scratch and returns the requested bytes.
// To implement io.Reader, we need to ask for len(c.buf) + len(p)
// bytes and copy the last derived len(p) bytes to p.
// We use c.buf to know how many bytes we've already derived and
// to avoid allocating the whole output buffer on each call.
prevLen := len(c.buf)
needLen := len(p)
remains := 255*c.hashLen - prevLen
// Check whether enough data can be generated.
if remains < needLen {
return 0, errors.New("hkdf: entropy limit reached")
}
c.buf = append(c.buf, make([]byte, needLen)...)
outLen := prevLen + needLen
if _, err := ossl.EVP_PKEY_derive(c.ctx, base(c.buf), &outLen); err != nil {
return 0, err
}
n := copy(p, c.buf[prevLen:outLen])
return n, nil
}
// hkdfAllZerosSalt is a preallocated buffer of zeros used in ExtractHKDF().
// The size should be kept as large as the output length of any hash algorithm
// used with HKDF.
var hkdfAllZerosSalt [64]byte
// ExtractHDKF implements the HDKF extract step.
// If salt is nil, then this function replaces it internally with a buffer of
// zeros whose length equals the output length of the specified hash algorithm.
func ExtractHKDF(h func() hash.Hash, secret, salt []byte) ([]byte, error) {
if !SupportsHKDF() {
return nil, errUnsupportedVersion()
}
md, err := hashFuncToMD(h)
if err != nil {
return nil, err
}
// If calling code specifies nil salt, replace it with a buffer of hashLen
// zeros, as specified in RFC 5896 and as OpenSSL EVP_KDF-HKDF documentation
// instructs. Take a slice of a preallocated buffer to avoid allocating new
// buffer per call, but fall back to allocating a buffer if preallocated
// buffer is not large enough.
if salt == nil {
hlen := h().Size()
if hlen > len(hkdfAllZerosSalt) {
salt = make([]byte, hlen)
} else {
salt = hkdfAllZerosSalt[:hlen]
}
}
switch vMajor {
case 1:
ctx, err := newHKDFCtx1(md, ossl.EVP_KDF_HKDF_MODE_EXTRACT_ONLY, secret, salt, nil, nil)
if err != nil {
return nil, err
}
defer ossl.EVP_PKEY_CTX_free(ctx)
var keylen int
if _, err := ossl.EVP_PKEY_derive(ctx, nil, &keylen); err != nil {
return nil, err
}
out := make([]byte, keylen)
if _, err := ossl.EVP_PKEY_derive(ctx, base(out), &keylen); err != nil {
return nil, err
}
return out[:keylen], nil
case 3:
ctx, err := newHKDFCtx3(md, ossl.EVP_KDF_HKDF_MODE_EXTRACT_ONLY, secret, salt, nil, nil)
if err != nil {
return nil, err
}
defer ossl.EVP_KDF_CTX_free(ctx)
size, err := ossl.EVP_KDF_CTX_get_kdf_size(ctx)
if err != nil {
return nil, err
}
out := make([]byte, size)
if _, err := ossl.EVP_KDF_derive(ctx, base(out), len(out), nil); err != nil {
return nil, err
}
return out, nil
default:
panic(errUnsupportedVersion())
}
}
// ExpandHKDFOneShot derives a key from the given hash, key, and optional context info.
func ExpandHKDFOneShot(h func() hash.Hash, pseudorandomKey, info []byte, keyLength int) ([]byte, error) {
if !SupportsHKDF() {
return nil, errUnsupportedVersion()
}
md, err := hashFuncToMD(h)
if err != nil {
return nil, err
}
out := make([]byte, keyLength)
switch vMajor {
case 1:
ctx, err := newHKDFCtx1(md, ossl.EVP_KDF_HKDF_MODE_EXPAND_ONLY, nil, nil, pseudorandomKey, info)
if err != nil {
return nil, err
}
defer ossl.EVP_PKEY_CTX_free(ctx)
keylen := keyLength
if _, err := ossl.EVP_PKEY_derive(ctx, base(out), &keylen); err != nil {
return nil, err
}
case 3:
ctx, err := newHKDFCtx3(md, ossl.EVP_KDF_HKDF_MODE_EXPAND_ONLY, nil, nil, pseudorandomKey, info)
if err != nil {
return nil, err
}
defer ossl.EVP_KDF_CTX_free(ctx)
if _, err := ossl.EVP_KDF_derive(ctx, base(out), keyLength, nil); err != nil {
return nil, err
}
default:
panic(errUnsupportedVersion())
}
return out, nil
}
func ExpandHKDF(h func() hash.Hash, pseudorandomKey, info []byte) (io.Reader, error) {
if !SupportsHKDF() {
return nil, errUnsupportedVersion()
}
md, err := hashFuncToMD(h)
if err != nil {
return nil, err
}
size := int(ossl.EVP_MD_get_size(md))
switch vMajor {
case 1:
ctx, err := newHKDFCtx1(md, ossl.EVP_KDF_HKDF_MODE_EXPAND_ONLY, nil, nil, pseudorandomKey, info)
if err != nil {
return nil, err
}
c := &hkdf1{ctx: ctx, hashLen: size}
runtime.SetFinalizer(c, (*hkdf1).finalize)
return c, nil
case 3:
ctx, err := newHKDFCtx3(md, ossl.EVP_KDF_HKDF_MODE_EXPAND_ONLY, nil, nil, pseudorandomKey, info)
if err != nil {
return nil, err
}
c := &hkdf3{ctx: ctx, hashLen: size}
runtime.SetFinalizer(c, (*hkdf3).finalize)
return c, nil
default:
panic(errUnsupportedVersion())
}
}
type hkdf3 struct {
ctx ossl.EVP_KDF_CTX_PTR
hashLen int
buf []byte
}
func (c *hkdf3) finalize() {
if c.ctx != nil {
ossl.EVP_KDF_CTX_free(c.ctx)
}
}
// fetchHKDF3 fetches the HKDF algorithm.
// It is safe to call this function concurrently.
// The returned EVP_KDF_PTR shouldn't be freed.
var fetchHKDF3 = sync.OnceValues(func() (ossl.EVP_KDF_PTR, error) {
checkMajorVersion(3)
kdf, err := ossl.EVP_KDF_fetch(nil, _OSSL_KDF_NAME_HKDF.ptr(), nil)
if err != nil {
return nil, err
}
return kdf, nil
})
// newHKDFCtx3 implements HKDF for OpenSSL 3 using the EVP_KDF API.
func newHKDFCtx3(md ossl.EVP_MD_PTR, mode int32, secret, salt, pseudorandomKey, info []byte) (_ ossl.EVP_KDF_CTX_PTR, err error) {
checkMajorVersion(3)
kdf, err := fetchHKDF3()
if err != nil {
return nil, err
}
ctx, err := ossl.EVP_KDF_CTX_new(kdf)
if err != nil {
return nil, err
}
defer func() {
if err != nil {
ossl.EVP_KDF_CTX_free(ctx)
}
}()
bld, err := newParamBuilder()
if err != nil {
return ctx, err
}
bld.addUTF8String(_OSSL_KDF_PARAM_DIGEST, ossl.EVP_MD_get0_name(md), 0)
bld.addInt32(_OSSL_KDF_PARAM_MODE, int32(mode))
if len(secret) > 0 {
bld.addOctetString(_OSSL_KDF_PARAM_KEY, secret)
}
if len(salt) > 0 {
bld.addOctetString(_OSSL_KDF_PARAM_SALT, salt)
}
if len(pseudorandomKey) > 0 {
bld.addOctetString(_OSSL_KDF_PARAM_KEY, pseudorandomKey)
}
if len(info) > 0 {
bld.addOctetString(_OSSL_KDF_PARAM_INFO, info)
}
params, err := bld.build()
if err != nil {
return ctx, err
}
defer ossl.OSSL_PARAM_free(params)
if _, err := ossl.EVP_KDF_CTX_set_params(ctx, params); err != nil {
return ctx, err
}
return ctx, nil
}
func (c *hkdf3) Read(p []byte) (int, error) {
defer runtime.KeepAlive(c)
// EVP_KDF_derive doesn't support incremental output, each call
// derives the key from scratch and returns the requested bytes.
// To implement io.Reader, we need to ask for len(c.buf) + len(p)
// bytes and copy the last derived len(p) bytes to p.
// We use c.buf to know how many bytes we've already derived and
// to avoid allocating the whole output buffer on each call.
prevLen := len(c.buf)
needLen := len(p)
remains := 255*c.hashLen - prevLen
// Check whether enough data can be generated.
if remains < needLen {
return 0, errors.New("hkdf: entropy limit reached")
}
c.buf = append(c.buf, make([]byte, needLen)...)
outLen := prevLen + needLen
if _, err := ossl.EVP_KDF_derive(c.ctx, base(c.buf), outLen, nil); err != nil {
return 0, err
}
n := copy(p, c.buf[prevLen:outLen])
return n, nil
}