github.com/yacovm/fabric@v2.0.0-alpha.0.20191128145320-c5d4087dc723+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  	// newCertKeyPair returns a certificate and private key pair and nil,
    33  	// or nil, error in case of failure
    34  	// The certificate is signed by the CA and is used for TLS client authentication
    35  	NewClientCertKeyPair() (*CertKeyPair, error)
    36  
    37  	// NewServerCertKeyPair returns a CertKeyPair and nil,
    38  	// with a given custom SAN.
    39  	// The certificate is signed by the CA.
    40  	// Returns nil, error in case of failure
    41  	NewServerCertKeyPair(host string) (*CertKeyPair, error)
    42  }
    43  
    44  type ca struct {
    45  	caCert *CertKeyPair
    46  }
    47  
    48  func NewCA() (CA, error) {
    49  	c := &ca{}
    50  	var err error
    51  	c.caCert, err = newCertKeyPair(true, false, "", nil, nil)
    52  	if err != nil {
    53  		return nil, err
    54  	}
    55  	return c, nil
    56  }
    57  
    58  // CertBytes returns the certificate of the CA in PEM encoding
    59  func (c *ca) CertBytes() []byte {
    60  	return c.caCert.Cert
    61  }
    62  
    63  // newClientCertKeyPair returns a certificate and private key pair and nil,
    64  // or nil, error in case of failure
    65  // The certificate is signed by the CA and is used as a client TLS certificate
    66  func (c *ca) NewClientCertKeyPair() (*CertKeyPair, error) {
    67  	return newCertKeyPair(false, false, "", c.caCert.Signer, c.caCert.TLSCert)
    68  }
    69  
    70  // newServerCertKeyPair returns a certificate and private key pair and nil,
    71  // or nil, error in case of failure
    72  // The certificate is signed by the CA and is used as a server TLS certificate
    73  func (c *ca) NewServerCertKeyPair(host string) (*CertKeyPair, error) {
    74  	keypair, err := newCertKeyPair(false, true, host, c.caCert.Signer, c.caCert.TLSCert)
    75  	if err != nil {
    76  		return nil, err
    77  	}
    78  	return keypair, nil
    79  }