// LoadCert loads the certificate in the given location
326899
func LoadCert(location string) (cert []byte, err error) {
	cert, err = ioutil.ReadFile(filepath.Clean(location + "/server.cert"))
	if err != nil {
		return
	}
	return
}
137247
func LoadTokenSignKey() error {
	tokenSignKeyPath := os.Getenv(EnvTokenSignKey)
	if tokenSignKeyPath == "" {
		tokenSignKeyPath = TokenSignKeyDefault
	}
	tokenSignKeyPem, err := ioutil.ReadFile(tokenSignKeyPath)
	if err != nil {
		return err
	}
	pemBlock, _ := pem.Decode(tokenSignKeyPem)
	if pemBlock.Type != "RSA PRIVATE KEY" {
		return errors.New("Key type was not RSA PRIVATE KEY")
	}
	tokenSignKey, err := x509.ParsePKCS1PrivateKey(pemBlock.Bytes)
	if err != nil {
		return err
	}
	TokenSignKey = tokenSignKey
	return nil
}
793321
func validateCACertAndKey(l certKeyLocation) error {
	if err := validateCACert(l); err != nil {
		return err
	}

	_, err := pkiutil.TryLoadKeyFromDisk(l.pkiDir, l.caBaseName)
	if err != nil {
		return errors.Wrapf(err, "failure loading key for %s", l.uxName)
	}
	return nil
}
1027049
func LoadClientCertificate(certFile string, keyFile string) (*tls.Certificate, error) {
	if certFile != "" && keyFile != "" {
		cert, err := tls.LoadX509KeyPair(certFile, keyFile)
		if err != nil {
			log.Critical("Unable to read client certificate from file: %s or key from file: %s", certFile, keyFile)
			return nil, err
		}
		log.Debug("Client certificate loaded ")
		return &cert, nil
	}
	return nil, nil
}
218845
func LoadCAPath(path string) (*x509.CertPool, error) {
	result := x509.NewCertPool()

	// filepath.WalkFunc to traverse the directory structure, starting from input path
	// attempting to load certs into result in the process
	appendCerts := func(path string, info os.FileInfo, err error) error {
		// cascade errors to the end of the traversal,
		//  we fail early if there are files other than certs under path
		if err != nil {
			return err
		}

		// ignore dirs
		if info.IsDir() {
			return nil
		}

		// try and append certs from files
		if err := appendPEMCertsFromPath(result, path); err != nil {
			// fail if we can't append PEM certs or get no PEM certs from a file
			return err
		}

		return nil
	}

	// if we error while walking with appendCerts, don't return any certs
	if err := filepath.Walk(path, appendCerts); err != nil {
		return nil, err
	}

	return result, nil
}
162811
func (m *Manager) load() error {
	m.rw.Lock()
	defer m.rw.Unlock()

	domain := strings.TrimSuffix(m.Domain, ".")

	certKey, err := m.cachedKey(domain + keySuffix)
	if err != nil {
		return err
	}

	buf, err := ioutil.ReadFile(filepath.Join(m.CacheDir, domain+certSuffix))
	if err != nil {
		return err
	}

	var b *pem.Block
	var der [][]byte
	for {
		b, buf = pem.Decode(buf)
		if b == nil {
			break
		}
		if b.Type != "CERTIFICATE" {
			return ErrInvalidCertificate
		}
		der = append(der, b.Bytes)
		if buf == nil {
			break
		}
	}
	if len(der) == 0 {
		return ErrInvalidCertificate
	}

	leaf, err := parseCert(domain, der, certKey)
	if err != nil {
		return err
	}

	if time.Now().After(leaf.NotAfter) {
		return ErrCertificateExpired
	}

	m.cert = &tls.Certificate{
		Certificate: der,
		Leaf:        leaf,
		PrivateKey:  certKey,
	}

	return nil
}
857726
func LoadCertFromPEM(pemBytes []byte) (*x509.Certificate, error) {
	for len(pemBytes) > 0 {
		var block *pem.Block
		block, pemBytes = pem.Decode(pemBytes)
		if block == nil {
			return nil, errors.New("no certificates found in PEM data")
		}
		if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
			continue
		}

		cert, err := x509.ParseCertificate(block.Bytes)
		if err != nil {
			continue
		}

		return cert, nil
	}

	return nil, errors.New("no certificates found in PEM data")
}
404663
func loadCABundle(cafile string) (*x509.CertPool, error) {
	var pem []byte
	var err error

	if cafile == "" {
		pem, err = data.Asset("data/ca_bundle.pem")
	} else {
		pem, err = ioutil.ReadFile(cafile)

	}
	if err != nil {
		return nil, fmt.Errorf("unable to find CA bundle")
	}

	c := x509.NewCertPool()
	ok := c.AppendCertsFromPEM(pem)
	if !ok {
		return nil, fmt.Errorf("unable to load CA bundle from %s", cafile)
	}

	return c, nil
}
374083
func TryLoadCertAndKeyFromDisk(pkiPath, name string) (*x509.Certificate, crypto.Signer, error) {
	cert, err := TryLoadCertFromDisk(pkiPath, name)
	if err != nil {
		return nil, nil, errors.Wrap(err, "failed to load certificate")
	}

	key, err := TryLoadKeyFromDisk(pkiPath, name)
	if err != nil {
		return nil, nil, errors.Wrap(err, "failed to load key")
	}

	return cert, key, nil
}
71930
func (c *Client) GetCertAuthority(id services.CertAuthID, loadSigningKeys bool, opts ...services.MarshalOption) (services.CertAuthority, error) {
	if err := id.Check(); err != nil {
		return nil, trace.Wrap(err)
	}
	out, err := c.Get(c.Endpoint("authorities", string(id.Type), id.DomainName), url.Values{
		"load_keys": []string{fmt.Sprintf("%t", loadSigningKeys)},
	})
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return services.GetCertAuthorityMarshaler().UnmarshalCertAuthority(
		out.Bytes(), services.SkipValidation())
}
1011665
func Load(filename, password string) (tls.Certificate, error) {
	p12, err := ioutil.ReadFile(filename)
	if err != nil {
		return tls.Certificate{}, fmt.Errorf("Unable to load %s: %v", filename, err)
	}
	return Decode(p12, password)
}
115489
func LoadSystemCAs() (*x509.CertPool, error) {
	pool := x509.NewCertPool()

	for _, keychain := range certKeychains() {
		err := addCertsFromKeychain(pool, keychain)
		if err != nil {
			return nil, err
		}
	}

	return pool, nil
}
1033094
func LoadCAFile(caFile string) (*x509.CertPool, error) {
	pool := x509.NewCertPool()

	pem, err := ioutil.ReadFile(caFile)
	if err != nil {
		return nil, fmt.Errorf("Error loading CA File: %s", err)
	}

	ok := pool.AppendCertsFromPEM(pem)
	if !ok {
		return nil, fmt.Errorf("Error loading CA File: Couldn't parse PEM in: %s", caFile)
	}

	return pool, nil
}
591176
func loadX509KeyPair(certFile, keyFile string) (cert tls.Certificate, err error) {
	certPEMBlock, err := wkfs.ReadFile(certFile)
	if err != nil {
		return
	}
	keyPEMBlock, err := wkfs.ReadFile(keyFile)
	if err != nil {
		return
	}
	return tls.X509KeyPair(certPEMBlock, keyPEMBlock)
}
750480
func TryLoadCertFromDisk(pkiPath, name string) (*x509.Certificate, error) {
	certificatePath := pathForCert(pkiPath, name)

	certs, err := certutil.CertsFromFile(certificatePath)
	if err != nil {
		return nil, errors.Wrapf(err, "couldn't load the certificate file %s", certificatePath)
	}

	// We are only putting one certificate in the certificate pem file, so it's safe to just pick the first one
	// TODO: Support multiple certs here in order to be able to rotate certs
	cert := certs[0]

	// Check so that the certificate is valid now
	now := time.Now()
	if now.Before(cert.NotBefore) {
		return nil, errors.New("the certificate is not valid yet")
	}
	if now.After(cert.NotAfter) {
		return nil, errors.New("the certificate has expired")
	}

	return cert, nil
}
143104
func GenerateCert(location string, commonName string, hostnames ...string) error {
	privKey, err := LoadKeypair(location)
	if err != nil {
		return err
	}

	// Build Certificate
	notBefore := time.Now()
	notAfter := notBefore.Add(validFor)
	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		return err
	}
	template := x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			CommonName:   commonName,
			Organization: []string{"The Things Network"},
		},
		IsCA:                  true,
		NotBefore:             notBefore,
		NotAfter:              notAfter,
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
		BasicConstraintsValid: true,
	}
	for _, h := range hostnames {
		if ip := net.ParseIP(h); ip != nil {
			template.IPAddresses = append(template.IPAddresses, ip)
		} else {
			template.DNSNames = append(template.DNSNames, h)
		}
	}

	// Generate certificate
	certBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, privKey.Public(), privKey)
	if err != nil {
		return err
	}
	certPEM := pem.EncodeToMemory(&pem.Block{
		Type:  "CERTIFICATE",
		Bytes: certBytes,
	})

	err = ioutil.WriteFile(filepath.Clean(location+"/server.cert"), certPEM, 0644)
	if err != nil {
		return err
	}

	return nil
}
580930
func (c *Certs) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
	c.RLock()
	defer c.RUnlock()
	return &c.cert, nil
}