github.com/hyperledger-labs/bdls@v2.1.1+incompatible/common/crypto/tlsgen/ca.go (about) 1 /* 2 Copyright IBM Corp. All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package tlsgen 8 9 import ( 10 "crypto" 11 "crypto/x509" 12 ) 13 14 // CertKeyPair denotes a TLS certificate and corresponding key, 15 // both PEM encoded 16 type CertKeyPair struct { 17 // Cert is the certificate, PEM encoded 18 Cert []byte 19 // Key is the key corresponding to the certificate, PEM encoded 20 Key []byte 21 22 crypto.Signer 23 TLSCert *x509.Certificate 24 } 25 26 // CA defines a certificate authority that can generate 27 // certificates signed by it 28 type CA interface { 29 // CertBytes returns the certificate of the CA in PEM encoding 30 CertBytes() []byte 31 32 NewIntermediateCA() (CA, error) 33 34 // newCertKeyPair returns a certificate and private key pair and nil, 35 // or nil, error in case of failure 36 // The certificate is signed by the CA and is used for TLS client authentication 37 NewClientCertKeyPair() (*CertKeyPair, error) 38 39 // NewServerCertKeyPair returns a CertKeyPair and nil, 40 // with a given custom SAN. 41 // The certificate is signed by the CA. 42 // Returns nil, error in case of failure 43 NewServerCertKeyPair(host string) (*CertKeyPair, error) 44 } 45 46 type ca struct { 47 caCert *CertKeyPair 48 } 49 50 func NewCA() (CA, error) { 51 c := &ca{} 52 var err error 53 c.caCert, err = newCertKeyPair(true, false, "", nil, nil) 54 if err != nil { 55 return nil, err 56 } 57 return c, nil 58 } 59 60 func (c *ca) NewIntermediateCA() (CA, error) { 61 intermediateCA := &ca{} 62 var err error 63 intermediateCA.caCert, err = newCertKeyPair(true, false, "", c.caCert.Signer, c.caCert.TLSCert) 64 if err != nil { 65 return nil, err 66 } 67 return intermediateCA, nil 68 } 69 70 // CertBytes returns the certificate of the CA in PEM encoding 71 func (c *ca) CertBytes() []byte { 72 return c.caCert.Cert 73 } 74 75 // newClientCertKeyPair returns a certificate and private key pair and nil, 76 // or nil, error in case of failure 77 // The certificate is signed by the CA and is used as a client TLS certificate 78 func (c *ca) NewClientCertKeyPair() (*CertKeyPair, error) { 79 return newCertKeyPair(false, false, "", c.caCert.Signer, c.caCert.TLSCert) 80 } 81 82 // newServerCertKeyPair returns a certificate and private key pair and nil, 83 // or nil, error in case of failure 84 // The certificate is signed by the CA and is used as a server TLS certificate 85 func (c *ca) NewServerCertKeyPair(host string) (*CertKeyPair, error) { 86 keypair, err := newCertKeyPair(false, true, host, c.caCert.Signer, c.caCert.TLSCert) 87 if err != nil { 88 return nil, err 89 } 90 return keypair, nil 91 }