-
Notifications
You must be signed in to change notification settings - Fork 1
/
servercert.go
57 lines (50 loc) · 1.56 KB
/
servercert.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
package cafiles
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"fmt"
"net"
"time"
"github.com/RealImage/bifrost"
"github.com/RealImage/bifrost/pkg/tinyca"
)
func CreateServerCertificate(
caCert *bifrost.Certificate,
caKey *ecdsa.PrivateKey,
) (*bifrost.Certificate, *ecdsa.PrivateKey, error) {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, nil, fmt.Errorf("error generating server key: %w", err)
}
template := x509.CertificateRequest{
Subject: pkix.Name{
CommonName: bifrost.UUID(caCert.Namespace, &key.PublicKey).String(),
Organization: []string{caCert.Namespace.String()},
},
SignatureAlgorithm: bifrost.SignatureAlgorithm,
DNSNames: []string{"localhost"},
IPAddresses: []net.IP{net.ParseIP("127.0.0.0")},
}
csrBytes, err := x509.CreateCertificateRequest(rand.Reader, &template, key)
if err != nil {
return nil, nil, fmt.Errorf("error creating certificate request: %w", err)
}
ca, err := tinyca.New(caCert, caKey, time.Hour*24*365)
if err != nil {
return nil, nil, err
}
keyUsage := x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment
extKeyUsage := []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}
certBytes, err := ca.IssueCertificate(csrBytes, keyUsage, extKeyUsage)
if err != nil {
return nil, nil, fmt.Errorf("error issuing server certificate: %w", err)
}
cert, err := bifrost.ParseCertificate(certBytes)
if err != nil {
return nil, nil, fmt.Errorf("error parsing server certificate: %w", err)
}
return cert, key, nil
}