github.com/mattyw/juju@v0.0.0-20140610034352-732aecd63861/testing/cert.go (about)

     1  // Copyright 2012, 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package testing
     5  
     6  import (
     7  	"crypto/rsa"
     8  	"crypto/tls"
     9  	"crypto/x509"
    10  	"fmt"
    11  	"time"
    12  
    13  	"github.com/juju/juju/cert"
    14  )
    15  
    16  func init() {
    17  	if err := verifyCertificates(); err != nil {
    18  		panic(err)
    19  	}
    20  }
    21  
    22  // CACert and CAKey make up a CA key pair.
    23  // CACertX509 and CAKeyRSA hold their parsed equivalents.
    24  // ServerCert and ServerKey hold a CA-signed server cert/key.
    25  var (
    26  	CACert, CAKey = mustNewCA()
    27  
    28  	CACertX509, CAKeyRSA = mustParseCertAndKey(CACert, CAKey)
    29  
    30  	ServerCert, ServerKey = mustNewServer()
    31  )
    32  
    33  func verifyCertificates() error {
    34  	_, err := tls.X509KeyPair([]byte(CACert), []byte(CAKey))
    35  	if err != nil {
    36  		return fmt.Errorf("bad CA cert key pair: %v", err)
    37  	}
    38  	_, err = tls.X509KeyPair([]byte(ServerCert), []byte(ServerKey))
    39  	if err != nil {
    40  		return fmt.Errorf("bad server cert key pair: %v", err)
    41  	}
    42  	return cert.Verify(ServerCert, CACert, time.Now())
    43  }
    44  
    45  func mustNewCA() (string, string) {
    46  	cert.KeyBits = 512
    47  	caCert, caKey, err := cert.NewCA("juju testing", time.Now().AddDate(10, 0, 0))
    48  	if err != nil {
    49  		panic(err)
    50  	}
    51  	return string(caCert), string(caKey)
    52  }
    53  
    54  func mustNewServer() (string, string) {
    55  	cert.KeyBits = 512
    56  	var hostnames []string
    57  	srvCert, srvKey, err := cert.NewServer(CACert, CAKey, time.Now().AddDate(10, 0, 0), hostnames)
    58  	if err != nil {
    59  		panic(err)
    60  	}
    61  	return string(srvCert), string(srvKey)
    62  }
    63  
    64  func mustParseCert(pemData string) *x509.Certificate {
    65  	cert, err := cert.ParseCert(pemData)
    66  	if err != nil {
    67  		panic(err)
    68  	}
    69  	return cert
    70  }
    71  
    72  func mustParseCertAndKey(certPEM, keyPEM string) (*x509.Certificate, *rsa.PrivateKey) {
    73  	cert, key, err := cert.ParseCertAndKey(certPEM, keyPEM)
    74  	if err != nil {
    75  		panic(err)
    76  	}
    77  	return cert, key
    78  }