-
Notifications
You must be signed in to change notification settings - Fork 47
/
cert_options.go
64 lines (52 loc) · 1.54 KB
/
cert_options.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
/*
Copyright (c) 2021 - Present. Blend Labs, Inc. All rights reserved
Use of this source code is governed by a MIT license that can be found in the LICENSE file.
*/
package certutil
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"math/big"
"time"
"github.com/blend/go-sdk/ex"
)
// CertOptions are required arguments when creating certificates.
type CertOptions struct {
x509.Certificate
PrivateKey *rsa.PrivateKey
NotBeforeProvider func() time.Time
NotAfterProvider func() time.Time
}
// ResolveCertOptions resolves the common create cert options.
func ResolveCertOptions(createOptions *CertOptions, options ...CertOption) error {
var err error
for _, option := range options {
if err = option(createOptions); err != nil {
return err
}
}
if createOptions.PrivateKey == nil {
createOptions.PrivateKey, err = rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return ex.New(err)
}
}
if createOptions.SerialNumber == nil {
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
createOptions.SerialNumber, err = rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return ex.New(err)
}
}
var output CertBundle
output.PrivateKey = createOptions.PrivateKey
output.PublicKey = &createOptions.PrivateKey.PublicKey
if createOptions.NotAfter.IsZero() && createOptions.NotAfterProvider != nil {
createOptions.NotAfter = createOptions.NotAfterProvider()
}
if createOptions.NotAfter.IsZero() && createOptions.NotAfterProvider != nil {
createOptions.NotAfter = createOptions.NotAfterProvider()
}
return nil
}