@@ -20,6 +20,7 @@ import (
2020 "crypto/elliptic"
2121 "crypto/rand"
2222 "crypto/x509"
23+ "crypto/x509/pkix"
2324 "math/big"
2425 "time"
2526)
@@ -44,3 +45,62 @@ func generateKey() (*ecdsa.PrivateKey, error) {
4445func generateSerialNumber () (* big.Int , error ) {
4546 return rand .Int (rand .Reader , new (big.Int ).Lsh (big .NewInt (1 ), 128 ))
4647}
48+
49+ func generateLeafCertificate (
50+ signer * x509.Certificate , signerPrivate * ecdsa.PrivateKey ,
51+ signeePublic * ecdsa.PublicKey , serialNumber * big.Int ,
52+ commonName string , dnsNames []string ,
53+ ) (* x509.Certificate , error ) {
54+ const leafExpiration = time .Hour * 24 * 365
55+ const leafStartValid = time .Hour * - 1
56+
57+ now := currentTime ()
58+ template := & x509.Certificate {
59+ BasicConstraintsValid : true ,
60+ DNSNames : dnsNames ,
61+ KeyUsage : x509 .KeyUsageDigitalSignature | x509 .KeyUsageKeyEncipherment ,
62+ NotBefore : now .Add (leafStartValid ),
63+ NotAfter : now .Add (leafExpiration ),
64+ SerialNumber : serialNumber ,
65+ SignatureAlgorithm : certificateSignatureAlgorithm ,
66+ Subject : pkix.Name {
67+ CommonName : commonName ,
68+ },
69+ }
70+
71+ bytes , err := x509 .CreateCertificate (rand .Reader , template , signer ,
72+ signeePublic , signerPrivate )
73+
74+ parsed , _ := x509 .ParseCertificate (bytes )
75+ return parsed , err
76+ }
77+
78+ func generateRootCertificate (
79+ privateKey * ecdsa.PrivateKey , serialNumber * big.Int ,
80+ ) (* x509.Certificate , error ) {
81+ const rootCommonName = "postgres-operator-ca"
82+ const rootExpiration = time .Hour * 24 * 365 * 10
83+ const rootStartValid = time .Hour * - 1
84+
85+ now := currentTime ()
86+ template := & x509.Certificate {
87+ BasicConstraintsValid : true ,
88+ IsCA : true ,
89+ KeyUsage : x509 .KeyUsageCertSign | x509 .KeyUsageCRLSign ,
90+ MaxPathLenZero : true , // there are no intermediate certificates
91+ NotBefore : now .Add (rootStartValid ),
92+ NotAfter : now .Add (rootExpiration ),
93+ SerialNumber : serialNumber ,
94+ SignatureAlgorithm : certificateSignatureAlgorithm ,
95+ Subject : pkix.Name {
96+ CommonName : rootCommonName ,
97+ },
98+ }
99+
100+ // A root certificate is self-signed, so pass in the template twice.
101+ bytes , err := x509 .CreateCertificate (rand .Reader , template , template ,
102+ privateKey .Public (), privateKey )
103+
104+ parsed , _ := x509 .ParseCertificate (bytes )
105+ return parsed , err
106+ }
0 commit comments