// CrossSignCACertificate takes a CA root certificate and generates an intermediate CA from it signed with the current root signer
178099
func (rca *RootCA) CrossSignCACertificate(otherCAPEM []byte) ([]byte, error) {
	signer, err := rca.Signer()
	if err != nil {
		return nil, err
	}

	// create a new cert with exactly the same parameters, including the public key and exact NotBefore and NotAfter
	template, err := helpers.ParseCertificatePEM(otherCAPEM)
	if err != nil {
		return nil, errors.New("could not parse new CA certificate")
	}

	if !template.IsCA {
		return nil, errors.New("certificate not a CA")
	}

	template.SignatureAlgorithm = signer.parsedCert.SignatureAlgorithm // make sure we can sign with the signer key
	derBytes, err := x509.CreateCertificate(cryptorand.Reader, template, signer.parsedCert, template.PublicKey, signer.cryptoSigner)
	if err != nil {
		return nil, errors.Wrap(err, "could not cross-sign new CA certificate using old CA material")
	}

	return pem.EncodeToMemory(&pem.Block{
		Type:  "CERTIFICATE",
		Bytes: derBytes,
	}), nil
}
181432
func (s *ModifyDBInstanceInput) SetCACertificateIdentifier(v string) *ModifyDBInstanceInput {
	s.CACertificateIdentifier = &v
	return s
}
133654
func GetCertificateSigningRequest(d Depot, name string) (crt *pkix.CertificateSigningRequest, err error) {
	b, err := d.Get(CsrTag(name))
	if err != nil {
		return nil, err
	}
	return pkix.NewCertificateSigningRequestFromPEM(b)
}
484260
func (s *Server) WithCertificate(cert *tls.Certificate) *Server {
	s.cert = cert
	return s
}
44472
func (h finishedHash) selectClientCertSignatureAlgorithm(serverList []signatureAndHash, sigType uint8) (signatureAndHash, error) {
	if h.version < VersionTLS12 {
		// Nothing to negotiate before TLS 1.2.
		return signatureAndHash{signature: sigType}, nil
	}

	for _, v := range serverList {
		if v.signature == sigType && isSupportedSignatureAndHash(v, supportedSignatureAlgorithms) {
			return v, nil
		}
	}
	return signatureAndHash{}, errors.New("tls: no supported signature algorithm found for signing client certificate")
}
997793
func (c *IdentityConfig) CAClientCert(org string) ([]byte, bool) {
	caConfigs, ok := c.caConfigsByOrg[strings.ToLower(org)]
	if ok {
		//for now, we're only loading the first Cert Authority by default.
		return caConfigs[0].TLSCAClientCert, true
	}

	return nil, false
}
799916
func (i *macIdentity) Certificate() (*x509.Certificate, error) {
	certRef, err := i.getCertRef()
	if err != nil {
		return nil, err
	}

	crt, err := exportCertRef(certRef)
	if err != nil {
		return nil, err
	}

	i.crt = crt

	return i.crt, nil
}
1074124
func signCertificate(data *dataBundle) (*certutil.ParsedCertBundle, error) {
	switch {
	case data == nil:
		return nil, errutil.UserError{Err: "nil data bundle given to signCertificate"}
	case data.params == nil:
		return nil, errutil.UserError{Err: "nil parameters given to signCertificate"}
	case data.signingBundle == nil:
		return nil, errutil.UserError{Err: "nil signing bundle given to signCertificate"}
	case data.csr == nil:
		return nil, errutil.UserError{Err: "nil csr given to signCertificate"}
	}

	err := data.csr.CheckSignature()
	if err != nil {
		return nil, errutil.UserError{Err: "request signature invalid"}
	}

	result := &certutil.ParsedCertBundle{}

	serialNumber, err := certutil.GenerateSerialNumber()
	if err != nil {
		return nil, err
	}

	marshaledKey, err := x509.MarshalPKIXPublicKey(data.csr.PublicKey)
	if err != nil {
		return nil, errutil.InternalError{Err: fmt.Sprintf("error marshalling public key: %s", err)}
	}
	subjKeyID := sha1.Sum(marshaledKey)

	caCert := data.signingBundle.Certificate

	certTemplate := &x509.Certificate{
		SerialNumber:   serialNumber,
		Subject:        data.params.Subject,
		NotBefore:      time.Now().Add(-30 * time.Second),
		NotAfter:       data.params.NotAfter,
		SubjectKeyId:   subjKeyID[:],
		AuthorityKeyId: caCert.SubjectKeyId,
	}
	if data.params.NotBeforeDuration > 0 {
		certTemplate.NotBefore = time.Now().Add(-1 * data.params.NotBeforeDuration)
	}

	switch data.signingBundle.PrivateKeyType {
	case certutil.RSAPrivateKey:
		certTemplate.SignatureAlgorithm = x509.SHA256WithRSA
	case certutil.ECPrivateKey:
		certTemplate.SignatureAlgorithm = x509.ECDSAWithSHA256
	}

	if data.params.UseCSRValues {
		certTemplate.Subject = data.csr.Subject
		certTemplate.Subject.ExtraNames = certTemplate.Subject.Names

		certTemplate.DNSNames = data.csr.DNSNames
		certTemplate.EmailAddresses = data.csr.EmailAddresses
		certTemplate.IPAddresses = data.csr.IPAddresses
		certTemplate.URIs = data.csr.URIs

		for _, name := range data.csr.Extensions {
			if !name.Id.Equal(oidExtensionBasicConstraints) {
				certTemplate.ExtraExtensions = append(certTemplate.ExtraExtensions, name)
			}
		}

	} else {
		certTemplate.DNSNames = data.params.DNSNames
		certTemplate.EmailAddresses = data.params.EmailAddresses
		certTemplate.IPAddresses = data.params.IPAddresses
		certTemplate.URIs = data.params.URIs
	}

	if err := handleOtherSANs(certTemplate, data.params.OtherSANs); err != nil {
		return nil, errutil.InternalError{Err: errwrap.Wrapf("error marshaling other SANs: {{err}}", err).Error()}
	}

	addPolicyIdentifiers(data, certTemplate)

	addKeyUsages(data, certTemplate)

	addExtKeyUsageOids(data, certTemplate)

	var certBytes []byte

	certTemplate.IssuingCertificateURL = data.params.URLs.IssuingCertificates
	certTemplate.CRLDistributionPoints = data.params.URLs.CRLDistributionPoints
	certTemplate.OCSPServer = data.signingBundle.URLs.OCSPServers

	if data.params.IsCA {
		certTemplate.BasicConstraintsValid = true
		certTemplate.IsCA = true

		if data.signingBundle.Certificate.MaxPathLen == 0 &&
			data.signingBundle.Certificate.MaxPathLenZero {
			return nil, errutil.UserError{Err: "signing certificate has a max path length of zero, and cannot issue further CA certificates"}
		}

		certTemplate.MaxPathLen = data.params.MaxPathLength
		if certTemplate.MaxPathLen == 0 {
			certTemplate.MaxPathLenZero = true
		}
	} else if data.params.BasicConstraintsValidForNonCA {
		certTemplate.BasicConstraintsValid = true
		certTemplate.IsCA = false
	}

	if len(data.params.PermittedDNSDomains) > 0 {
		certTemplate.PermittedDNSDomains = data.params.PermittedDNSDomains
		certTemplate.PermittedDNSDomainsCritical = true
	}

	certBytes, err = x509.CreateCertificate(rand.Reader, certTemplate, caCert, data.csr.PublicKey, data.signingBundle.PrivateKey)

	if err != nil {
		return nil, errutil.InternalError{Err: fmt.Sprintf("unable to create certificate: %s", err)}
	}

	result.CertificateBytes = certBytes
	result.Certificate, err = x509.ParseCertificate(certBytes)
	if err != nil {
		return nil, errutil.InternalError{Err: fmt.Sprintf("unable to parse created certificate: %s", err)}
	}

	result.CAChain = data.signingBundle.GetCAChain()

	return result, nil
}
851145
func NewRootCA(rootCertBytes, signCertBytes, signKeyBytes []byte, certExpiry time.Duration, intermediates []byte) (RootCA, error) {
	// Parse all the certificates in the cert bundle
	parsedCerts, err := helpers.ParseCertificatesPEM(rootCertBytes)
	if err != nil {
		return RootCA{}, errors.Wrap(err, "invalid root certificates")
	}
	// Check to see if we have at least one valid cert
	if len(parsedCerts) < 1 {
		return RootCA{}, errors.New("no valid root CA certificates found")
	}

	// Create a Pool with all of the certificates found
	pool := x509.NewCertPool()
	for _, cert := range parsedCerts {
		if err := validateSignatureAlgorithm(cert); err != nil {
			return RootCA{}, err
		}
		// Check to see if all of the certificates are valid, self-signed root CA certs
		selfpool := x509.NewCertPool()
		selfpool.AddCert(cert)
		if _, err := cert.Verify(x509.VerifyOptions{Roots: selfpool}); err != nil {
			return RootCA{}, errors.Wrap(err, "error while validating Root CA Certificate")
		}
		pool.AddCert(cert)
	}

	// Calculate the digest for our Root CA bundle
	digest := digest.FromBytes(rootCertBytes)

	// The intermediates supplied must be able to chain up to the root certificates, so that when they are appended to
	// a leaf certificate, the leaf certificate can be validated through the intermediates to the root certificates.
	var intermediatePool *x509.CertPool
	var parsedIntermediates []*x509.Certificate
	if len(intermediates) > 0 {
		parsedIntermediates, _, err = ValidateCertChain(pool, intermediates, false)
		if err != nil {
			return RootCA{}, errors.Wrap(err, "invalid intermediate chain")
		}
		intermediatePool = x509.NewCertPool()
		for _, cert := range parsedIntermediates {
			intermediatePool.AddCert(cert)
		}
	}

	var localSigner *LocalSigner
	if len(signKeyBytes) != 0 || len(signCertBytes) != 0 {
		localSigner, err = newLocalSigner(signKeyBytes, signCertBytes, certExpiry, pool, intermediatePool)
		if err != nil {
			return RootCA{}, err
		}

		// If a signer is provided and there are intermediates, then either the first intermediate would be the signer CA
		// certificate (in which case it'd have the same subject and public key), or it would be a cross-signed
		// intermediate with the same subject and public key as our signing CA certificate (which could be either an
		// intermediate cert or a self-signed root cert).
		if len(parsedIntermediates) > 0 && (!bytes.Equal(parsedIntermediates[0].RawSubject, localSigner.parsedCert.RawSubject) ||
			!bytes.Equal(parsedIntermediates[0].RawSubjectPublicKeyInfo, localSigner.parsedCert.RawSubjectPublicKeyInfo)) {
			return RootCA{}, errors.New(
				"invalid intermediate chain - the first intermediate must have the same subject and public key as the signing cert")
		}
	}

	return RootCA{signer: localSigner, Intermediates: intermediates, Digest: digest, Certs: rootCertBytes, Pool: pool}, nil
}
320385
func (s *Certificate) SetCertificateType(v string) *Certificate {
	s.CertificateType = &v
	return s
}
1104326
func GenerateClientCertificate() (*Certificate, error) {
	cert, key, err := shared.GenerateMemCert(true)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return NewCertificate(cert, key), nil
}
263273
func (cfg *TLSConfig) TLSCert() (*x509.Certificate, bool, error) {

	block, _ := pem.Decode(cfg.bytes)

	if block != nil {
		pub, err := x509.ParseCertificate(block.Bytes)
		if err != nil {
			return nil, false, errors.Wrap(err, "certificate parsing failed")
		}

		return pub, true, nil
	}

	//no cert found and there is no error
	return nil, false, 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
}
958081
func (s *ProjectEnvironment) SetCertificate(v string) *ProjectEnvironment {
	s.Certificate = &v
	return s
}
811647
func (sa *StorageAuthority) AddCertificate(_ context.Context, certDER []byte, regID int64, _ []byte, _ *time.Time) (digest string, err error) {
	return
}
523888
func (e *EdgeCrosser) ChainCrossingSign(d Point) Crossing {
	// For there to be an edge crossing, the triangles ACB, CBD, BDA, DAC must
	// all be oriented the same way (CW or CCW). We keep the orientation of ACB
	// as part of our state. When each new point D arrives, we compute the
	// orientation of BDA and check whether it matches ACB. This checks whether
	// the points C and D are on opposite sides of the great circle through AB.

	// Recall that triageSign is invariant with respect to rotating its
	// arguments, i.e. ABD has the same orientation as BDA.
	bda := triageSign(e.a, e.b, d)
	if e.acb == -bda && bda != Indeterminate {
		// The most common case -- triangles have opposite orientations. Save the
		// current vertex D as the next vertex C, and also save the orientation of
		// the new triangle ACB (which is opposite to the current triangle BDA).
		e.c = d
		e.acb = -bda
		return DoNotCross
	}
	return e.crossingSign(d, bda)
}
779502
func (s *X509Signer) Certificate(ctx context.Context) ([]byte, error) {
	if err := s.Validate(); err != nil {
		return nil, err
	}
	return s.certDer, nil
}