forked from bitnami-labs/sealed-secrets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
keys.go
85 lines (74 loc) · 2.47 KB
/
keys.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
package main
import (
"context"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"github.com/bitnami-labs/sealed-secrets/pkg/crypto"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
certUtil "k8s.io/client-go/util/cert"
"k8s.io/client-go/util/keyutil"
)
// SealedSecretsKeyLabel is that label used to locate active key pairs used to decrypt sealed secrets.
const SealedSecretsKeyLabel = "sealedsecrets.bitnami.com/sealed-secrets-key"
var (
// ErrPrivateKeyNotRSA is returned when the private key is not a valid RSA key.
ErrPrivateKeyNotRSA = errors.New("Private key is not an RSA key")
)
func generatePrivateKeyAndCert(keySize int) (*rsa.PrivateKey, *x509.Certificate, error) {
return crypto.GeneratePrivateKeyAndCert(keySize, *validFor, *myCN)
}
func readKey(secret v1.Secret) (*rsa.PrivateKey, []*x509.Certificate, error) {
key, err := keyutil.ParsePrivateKeyPEM(secret.Data[v1.TLSPrivateKeyKey])
if err != nil {
return nil, nil, err
}
switch rsaKey := key.(type) {
case *rsa.PrivateKey:
certs, err := certUtil.ParseCertsPEM(secret.Data[v1.TLSCertKey])
if err != nil {
return nil, nil, err
}
return rsaKey, certs, nil
default:
return nil, nil, ErrPrivateKeyNotRSA
}
}
type writeKeyOpt func(*writeKeyOpts)
type writeKeyOpts struct{ creationTime metav1.Time }
func writeKeyWithCreationTime(t metav1.Time) writeKeyOpt {
return func(opts *writeKeyOpts) { opts.creationTime = t }
}
func writeKey(ctx context.Context, client kubernetes.Interface, key *rsa.PrivateKey, certs []*x509.Certificate, namespace, label, prefix string, optSetters ...writeKeyOpt) (string, error) {
var opts writeKeyOpts
for _, o := range optSetters {
o(&opts)
}
certbytes := []byte{}
for _, cert := range certs {
certbytes = append(certbytes, pem.EncodeToMemory(&pem.Block{Type: certUtil.CertificateBlockType, Bytes: cert.Raw})...)
}
secret := v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Namespace: namespace,
GenerateName: prefix,
Labels: map[string]string{
label: "active",
},
CreationTimestamp: opts.creationTime,
},
Data: map[string][]byte{
v1.TLSPrivateKeyKey: pem.EncodeToMemory(&pem.Block{Type: keyutil.RSAPrivateKeyBlockType, Bytes: x509.MarshalPKCS1PrivateKey(key)}),
v1.TLSCertKey: certbytes,
},
Type: v1.SecretTypeTLS,
}
createdSecret, err := client.CoreV1().Secrets(namespace).Create(ctx, &secret, metav1.CreateOptions{})
if err != nil {
return "", err
}
return createdSecret.Name, nil
}