github.com/altoros/juju-vmware@v0.0.0-20150312064031-f19ae857ccca/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 gitjujutesting "github.com/juju/testing" 14 15 "github.com/juju/juju/cert" 16 ) 17 18 func init() { 19 if err := verifyCertificates(); err != nil { 20 panic(err) 21 } 22 } 23 24 // CACert and CAKey make up a CA key pair. 25 // CACertX509 and CAKeyRSA hold their parsed equivalents. 26 // ServerCert and ServerKey hold a CA-signed server cert/key. 27 // Certs holds the certificates and keys required to make a secure 28 // connection to a Mongo database. 29 var ( 30 CACert, CAKey = mustNewCA() 31 32 CACertX509, CAKeyRSA = mustParseCertAndKey(CACert, CAKey) 33 34 ServerCert, ServerKey = mustNewServer() 35 36 Certs = serverCerts() 37 ) 38 39 func verifyCertificates() error { 40 _, err := tls.X509KeyPair([]byte(CACert), []byte(CAKey)) 41 if err != nil { 42 return fmt.Errorf("bad CA cert key pair: %v", err) 43 } 44 _, err = tls.X509KeyPair([]byte(ServerCert), []byte(ServerKey)) 45 if err != nil { 46 return fmt.Errorf("bad server cert key pair: %v", err) 47 } 48 return cert.Verify(ServerCert, CACert, time.Now()) 49 } 50 51 func mustNewCA() (string, string) { 52 cert.KeyBits = 512 53 caCert, caKey, err := cert.NewCA("juju testing", time.Now().AddDate(10, 0, 0)) 54 if err != nil { 55 panic(err) 56 } 57 return string(caCert), string(caKey) 58 } 59 60 func mustNewServer() (string, string) { 61 cert.KeyBits = 512 62 var hostnames []string 63 srvCert, srvKey, err := cert.NewServer(CACert, CAKey, time.Now().AddDate(10, 0, 0), hostnames) 64 if err != nil { 65 panic(err) 66 } 67 return string(srvCert), string(srvKey) 68 } 69 70 func mustParseCert(pemData string) *x509.Certificate { 71 cert, err := cert.ParseCert(pemData) 72 if err != nil { 73 panic(err) 74 } 75 return cert 76 } 77 78 func mustParseCertAndKey(certPEM, keyPEM string) (*x509.Certificate, *rsa.PrivateKey) { 79 cert, key, err := cert.ParseCertAndKey(certPEM, keyPEM) 80 if err != nil { 81 panic(err) 82 } 83 return cert, key 84 } 85 86 func serverCerts() *gitjujutesting.Certs { 87 serverCert, serverKey := mustParseCertAndKey(ServerCert, ServerKey) 88 return &gitjujutesting.Certs{ 89 CACert: CACertX509, 90 ServerCert: serverCert, 91 ServerKey: serverKey, 92 } 93 }