// DefaultCertificate generates random TLS certificates
165590
func DefaultCertificate() (*tls.Certificate, error) {
	randomBytes := make([]byte, 100)
	_, err := rand.Read(randomBytes)
	if err != nil {
		return nil, err
	}
	zBytes := sha256.Sum256(randomBytes)
	z := hex.EncodeToString(zBytes[:sha256.Size])
	domain := fmt.Sprintf("%s.%s.traefik.default", z[:32], z[32:])

	certPEM, keyPEM, err := KeyPair(domain, time.Time{})
	if err != nil {
		return nil, err
	}

	certificate, err := tls.X509KeyPair(certPEM, keyPEM)
	if err != nil {
		return nil, err
	}

	return &certificate, nil
}
222716
func (cap *CFSSL) CACertificate() ([]byte, error) {
	req := &info.Req{
		Label:   cap.Label,
		Profile: cap.Profile,
	}
	out, err := json.Marshal(req)
	if err != nil {
		return nil, err
	}

	resp, err := cap.remote.Info(out)
	if err != nil {
		return nil, err
	}

	return []byte(resp.Certificate), nil
}
909221
func (g *Cloud) CreateSslCertificate(sslCerts *compute.SslCertificate) (*compute.SslCertificate, error) {
	ctx, cancel := cloud.ContextWithCallTimeout()
	defer cancel()

	mc := newCertMetricContext("create")
	err := g.c.SslCertificates().Insert(ctx, meta.GlobalKey(sslCerts.Name), sslCerts)
	if err != nil {
		return nil, mc.Observe(err)
	}
	return g.GetSslCertificate(sslCerts.Name)
}
494223
func (client *Client) UploadServerCertificate(args *UploadServerCertificateArgs) (response *UploadServerCertificateResponse, err error) {
	response = &UploadServerCertificateResponse{}
	err = client.Invoke("UploadServerCertificate", args, response)
	if err != nil {
		return nil, err
	}
	return response, err
}
972815
func NewCertificate(cert *x509.Certificate) *Certificate {
	c := &Certificate{
		SKI:       fmt.Sprintf("%x", cert.SubjectKeyId),
		AKI:       fmt.Sprintf("%x", cert.AuthorityKeyId),
		Serial:    cert.SerialNumber.Bytes(),
		NotBefore: cert.NotBefore.Unix(),
		NotAfter:  cert.NotAfter.Unix(),
		Raw:       cert.Raw,
	}

	// Workaround the NOT NULL constraint.
	if cert.SerialNumber.Cmp(nullSerial) == 0 {
		c.Serial = []byte{0}
	}

	// Work around the fact that many early CA roots don't have an
	// SKI. This uses the method found in RFC 5280 Section 4.2.1.2
	// (1).
	if c.SKI == "" {
		ski, err := signer.ComputeSKI(cert)
		if err != nil {
			panic("invalid public key in root certificate")
		}

		c.SKI = fmt.Sprintf("%x", ski)
	}

	c.cert = cert

	return c
}
241961
func (c *Conn) PeerCertificate() (*Certificate, error) {
	c.mtx.Lock()
	defer c.mtx.Unlock()
	if c.is_shutdown {
		return nil, errors.New("connection closed")
	}
	x := C.SSL_get_peer_certificate(c.ssl)
	if x == nil {
		return nil, errors.New("no peer certificate found")
	}
	cert := &Certificate{x: x}
	runtime.SetFinalizer(cert, func(cert *Certificate) {
		C.X509_free(cert.x)
	})
	return cert, nil
}
1293742
func (m HostCertificateManager) InstallServerCertificate(ctx context.Context, cert string) error {
	req := types.InstallServerCertificate{
		This: m.Reference(),
		Cert: cert,
	}

	_, err := methods.InstallServerCertificate(ctx, m.Client(), &req)
	if err != nil {
		return err
	}

	// NotifyAffectedService is internal, not exposing as we don't have a use case other than with InstallServerCertificate
	// Without this call, hostd needs to be restarted to use the updated certificate
	// Note: using Refresh as it has the same struct/signature, we just need to use different xml name tags
	body := struct {
		Req *types.Refresh         `xml:"urn:vim25 NotifyAffectedServices,omitempty"`
		Res *types.RefreshResponse `xml:"urn:vim25 NotifyAffectedServicesResponse,omitempty"`
		methods.RefreshBody
	}{
		Req: &types.Refresh{This: m.Reference()},
	}

	return m.Client().RoundTrip(ctx, &body, &body)
}
703388
func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
	m.rw.RLock()
	defer m.rw.RUnlock()

	return m.cert, nil
}
341155
func (gServer *GRPCServer) ServerCertificate() tls.Certificate {
	return gServer.serverCertificate.Load().(tls.Certificate)
}
997988
func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) {
	if c.GetCertificate != nil &&
		(len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) {
		cert, err := c.GetCertificate(clientHello)
		if cert != nil || err != nil {
			return cert, err
		}
	}

	if len(c.Certificates) == 0 {
		return nil, errors.New("crypto/tls: no certificates configured")
	}

	if len(c.Certificates) == 1 || c.NameToCertificate == nil {
		// There's only one choice, so no point doing any work.
		return &c.Certificates[0], nil
	}

	name := strings.ToLower(clientHello.ServerName)
	for len(name) > 0 && name[len(name)-1] == '.' {
		name = name[:len(name)-1]
	}

	if cert, ok := c.NameToCertificate[name]; ok {
		return cert, nil
	}

	// try replacing labels in the name with wildcards until we get a
	// match.
	labels := strings.Split(name, ".")
	for i := range labels {
		labels[i] = "*"
		candidate := strings.Join(labels, ".")
		if cert, ok := c.NameToCertificate[candidate]; ok {
			return cert, nil
		}
	}

	// If nothing matches, return the first certificate.
	return &c.Certificates[0], nil
}
363750
func (s *AssociateWebsiteCertificateAuthorityInput) SetCertificate(v string) *AssociateWebsiteCertificateAuthorityInput {
	s.Certificate = &v
	return s
}
639484
func (ca *CertAuthority) GenerateCertificate(req CertificateRequest) ([]byte, error) {
	if err := req.CheckAndSetDefaults(); err != nil {
		return nil, trace.Wrap(err)
	}
	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	log.WithFields(logrus.Fields{
		"not_after":   req.NotAfter,
		"dns_names":   req.DNSNames,
		"common_name": req.Subject.CommonName,
		"org":         req.Subject.Organization,
		"org_unit":    req.Subject.OrganizationalUnit,
		"locality":    req.Subject.Locality,
	}).Infof("Generating TLS certificate %v.", req)

	template := &x509.Certificate{
		SerialNumber: serialNumber,
		Subject:      req.Subject,
		// NotBefore is one minute in the past to prevent "Not yet valid" errors on
		// time skewed clusters.
		NotBefore:   req.Clock.Now().UTC().Add(-1 * time.Minute),
		NotAfter:    req.NotAfter,
		KeyUsage:    x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
		// BasicConstraintsValid is true to not allow any intermediate certs.
		BasicConstraintsValid: true,
		IsCA: false,
	}

	// sort out principals into DNS names and IP addresses
	for i := range req.DNSNames {
		if ip := net.ParseIP(req.DNSNames[i]); ip != nil {
			template.IPAddresses = append(template.IPAddresses, ip)
		} else {
			template.DNSNames = append(template.DNSNames, req.DNSNames[i])
		}
	}

	certBytes, err := x509.CreateCertificate(rand.Reader, template, ca.Cert, req.PublicKey, ca.Signer)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certBytes}), nil
}
40448
func (ra *RegistrationAuthorityImpl) NewCertificate(ctx context.Context, req core.CertificateRequest, regID int64) (core.Certificate, error) {
	// Verify the CSR
	if err := csrlib.VerifyCSR(req.CSR, ra.maxNames, &ra.keyPolicy, ra.PA, ra.forceCNFromSAN, regID); err != nil {
		return core.Certificate{}, berrors.MalformedError(err.Error())
	}
	// NewCertificate provides an order ID of 0, indicating this is a classic ACME
	// v1 issuance request from the new certificate endpoint that is not
	// associated with an ACME v2 order.
	return ra.issueCertificate(ctx, req, accountID(regID), orderID(0))
}
679268
func (s *ViewerCertificate) SetCloudFrontDefaultCertificate(v bool) *ViewerCertificate {
	s.CloudFrontDefaultCertificate = &v
	return s
}
1291024
func (p *Config) GetCertificateFunc() func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
	return func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
		p.RLock()
		defer p.RUnlock()
		// First we check if this is a direct access to the public port. In this case
		// we will use the service public certificate. Otherwise, we will return the
		// enforcer certificate since this is internal access.
		if mconn, ok := clientHello.Conn.(*markedconn.ProxiedConnection); ok {
			ip, port := mconn.GetOriginalDestination()
			portContext, err := p.registry.RetrieveExposedServiceContext(ip, port, "")
			if err != nil {
				return nil, fmt.Errorf("service not available: %s %d", ip.String(), port)
			}
			service := portContext.Service
			if service.PublicNetworkInfo != nil && service.PublicNetworkInfo.Ports.Min == uint16(port) && len(service.PublicServiceCertificate) > 0 {
				tlsCert, err := tls.X509KeyPair(service.PublicServiceCertificate, service.PublicServiceCertificateKey)
				if err != nil {
					return nil, fmt.Errorf("failed to parse server certificate: %s", err)
				}
				return &tlsCert, nil
			}
		}
		if p.cert != nil {
			return p.cert, nil
		}
		return nil, fmt.Errorf("no cert available - cert is nil")
	}
}
1104326
func GenerateClientCertificate() (*Certificate, error) {
	cert, key, err := shared.GenerateMemCert(true)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return NewCertificate(cert, key), nil
}
289164
func NewCertificate(Subject string, Issuer string, IssueDate string, ExpirationDate string, SerialNumber string, Sha1Fingerprint string) *Certificate {
	s := new(Certificate)
	s.Subject = Subject
	s.Issuer = Issuer
	s.IssueDate = IssueDate
	s.ExpirationDate = ExpirationDate
	s.SerialNumber = SerialNumber
	s.Sha1Fingerprint = Sha1Fingerprint
	return s
}