github.com/jlmeeker/kismatic@v1.10.1-0.20180612190640-57f9005a1f1a/integration-tests/tls/ca.go (about) 1 package tls 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "io/ioutil" 7 "os" 8 "path/filepath" 9 10 "github.com/cloudflare/cfssl/csr" 11 "github.com/cloudflare/cfssl/initca" 12 "github.com/cloudflare/cfssl/log" 13 ) 14 15 func init() { 16 log.Level = log.LevelError 17 } 18 19 // The Subject contains the fields of the X.509 Subject 20 type Subject struct { 21 Country string 22 State string 23 Locality string 24 Organization string 25 OrganizationalUnit string 26 } 27 28 // NewCACert creates a new Certificate Authority and returns it's private key and public certificate. 29 func NewCACert(csrFile string, commonName string, subject Subject) (key, cert []byte, err error) { 30 // Open CSR file 31 f, err := os.Open(csrFile) 32 if os.IsNotExist(err) { 33 return nil, nil, fmt.Errorf("%q does not exist", csrFile) 34 } 35 if err != nil { 36 return nil, nil, fmt.Errorf("error opening %q", csrFile) 37 } 38 // Create CSR struct 39 caCSR := &csr.CertificateRequest{ 40 KeyRequest: csr.NewBasicKeyRequest(), 41 } 42 err = json.NewDecoder(f).Decode(caCSR) 43 if err != nil { 44 return nil, nil, fmt.Errorf("error decoding CSR: %v", err) 45 } 46 // Set the subject information 47 name := csr.Name{ 48 C: subject.Country, 49 ST: subject.State, 50 L: subject.Locality, 51 O: subject.Organization, 52 OU: subject.OrganizationalUnit, 53 } 54 caCSR.Names = []csr.Name{name} 55 caCSR.CN = commonName 56 // Generate CA Cert according to CSR 57 cert, _, key, err = initca.New(caCSR) 58 if err != nil { 59 return nil, nil, fmt.Errorf("error creating CA cert: %v", err) 60 } 61 return key, cert, nil 62 } 63 64 // ReadCACert read CA file 65 func ReadCACert(name, dir string) (key, cert []byte, err error) { 66 dest := filepath.Join(dir, keyName(name)) 67 key, errKey := ioutil.ReadFile(dest) 68 if errKey != nil { 69 return nil, nil, fmt.Errorf("error reading private key: %v", errKey) 70 } 71 dest = filepath.Join(dir, certName(name)) 72 cert, errCert := ioutil.ReadFile(dest) 73 if errCert != nil { 74 return nil, nil, fmt.Errorf("error reading certificate: %v", errKey) 75 } 76 return key, cert, nil 77 }