github.com/jlmeeker/kismatic@v1.10.1-0.20180612190640-57f9005a1f1a/pkg/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, expiry string) (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 caCSR.CN = commonName 47 caCSR.CA = &csr.CAConfig{Expiry: expiry} 48 // Generate CA Cert according to CSR 49 cert, _, key, err = initca.New(caCSR) 50 if err != nil { 51 return nil, nil, fmt.Errorf("error creating CA cert: %v", err) 52 } 53 return key, cert, nil 54 } 55 56 // ReadCACert read CA file 57 func ReadCACert(name, dir string) (key, cert []byte, err error) { 58 dest := filepath.Join(dir, keyName(name)) 59 key, errKey := ioutil.ReadFile(dest) 60 if errKey != nil { 61 return nil, nil, fmt.Errorf("error reading private key: %v", errKey) 62 } 63 dest = filepath.Join(dir, certName(name)) 64 cert, errCert := ioutil.ReadFile(dest) 65 if errCert != nil { 66 return nil, nil, fmt.Errorf("error reading certificate: %v", errKey) 67 } 68 return key, cert, nil 69 }