func (store *CertStore) Get(id int64) (*pkix.Certificate, error) { // FIXME // currently using serialnumber as id, should change to something which can be // mapped to (host, sn) pair filename := strconv.Itoa(int(id)) + ".crt" cert, err := pkix.NewCertificateFromPEMFile(store.RootDir + "/" + filename) if err != nil { return nil, err } return cert, nil }
func NewCA(rootDir string) (*CA, error) { // mkdir if needed if isPathNotExisted(rootDir + "/ca") { if err := os.MkdirAll(rootDir+"/ca", 0755); err != nil { return nil, err } } if isPathNotExisted(rootDir + "/certs") { if err := os.MkdirAll(rootDir+"/certs", 0755); err != nil { return nil, err } } var key *pkix.Key var certificate *pkix.Certificate var err error if isPathNotExisted(rootDir + "/ca/ca.key") { // gen priv key key, err = pkix.NewKey() if err != nil { return nil, err } if err := key.ToPEMFile(rootDir + "/ca/ca.key"); err != nil { return nil, err } // gen self-signed cert // should refactor, move to cert.go notBefore := time.Now() notAfter := notBefore.Add(time.Hour * 365 * 24) keyUsage := x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature extKeyUsage := []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth} template := &x509.Certificate{ SerialNumber: big.NewInt(1), Subject: gopkix.Name{ CommonName: "try.sbuca.com", }, NotBefore: notBefore, NotAfter: notAfter, KeyUsage: keyUsage, ExtKeyUsage: extKeyUsage, BasicConstraintsValid: true, } derBytes, err := x509.CreateCertificate(rand.Reader, template, template, key.PublicKey, key.PrivateKey) if err != nil { return nil, err } certificate, err = pkix.NewCertificateFromDER(derBytes) if err != nil { return nil, err } if err := certificate.ToPEMFile(rootDir + "/ca/ca.crt"); err != nil { return nil, err } } else { certificate, err = pkix.NewCertificateFromPEMFile(rootDir + "/ca/ca.crt") if err != nil { return nil, err } key, err = pkix.NewKeyFromPrivateKeyPEMFile(rootDir + "/ca/ca.key") if err != nil { return nil, err } } if isPathNotExisted(rootDir + "/ca/ca.srl") { ioutil.WriteFile(rootDir+"/ca/ca.srl", []byte("2"), 0644) } certStore := NewCertStore(rootDir + "/certs") newCA := &CA{ RootDir: rootDir, CertStore: certStore, Certificate: certificate, Key: key, } return newCA, nil }