certificationRequestToPEM - Convert a PKCS10CertificationRequest to PEM
format.

@param csr The Certificate to convert
@return An equivalent PEM format certificate.
@throws IOException
332281
private String certificationRequestToPEM(PKCS10CertificationRequest csr) throws IOException {
        PemObject pemCSR = new PemObject("CERTIFICATE REQUEST", csr.getEncoded());

        StringWriter str = new StringWriter();
        JcaPEMWriter pemWriter = new JcaPEMWriter(str);
        pemWriter.writeObject(pemCSR);
        pemWriter.close();
        str.close();
        return str.toString();
    }
581511
private static boolean issues(X509CertImpl cert, X509CRLImpl crl,
                                  String provider) throws IOException
    {
        boolean matched = false;

        AdaptableX509CertSelector issuerSelector =
                                    new AdaptableX509CertSelector();

        // check certificate's key usage
        boolean[] usages = cert.getKeyUsage();
        if (usages != null) {
            usages[6] = true;       // cRLSign
            issuerSelector.setKeyUsage(usages);
        }

        // check certificate's subject
        X500Principal crlIssuer = crl.getIssuerX500Principal();
        issuerSelector.setSubject(crlIssuer);

        /*
         * Facilitate certification path construction with authority
         * key identifier and subject key identifier.
         *
         * In practice, conforming CAs MUST use the key identifier method,
         * and MUST include authority key identifier extension in all CRLs
         * issued. [section 5.2.1, RFC 2459]
         */
        AuthorityKeyIdentifierExtension crlAKID = crl.getAuthKeyIdExtension();
        if (crlAKID != null) {
            issuerSelector.parseAuthorityKeyIdentifierExtension(crlAKID);
        }

        matched = issuerSelector.match(cert);

        // if AKID is unreliable, verify the CRL signature with the cert
        if (matched && (crlAKID == null ||
                cert.getAuthorityKeyIdentifierExtension() == null)) {
            try {
                crl.verify(cert.getPublicKey(), provider);
                matched = true;
            } catch (GeneralSecurityException e) {
                matched = false;
            }
        }

        return matched;
    }
729761
def ocsp_responder_certificate_path():
    
    certificate_path = getattr(settings, 'ESTEID_OCSP_RESPONDER_CERTIFICATE_PATH', 'TEST_of_SK_OCSP_RESPONDER_2011.pem')

    if certificate_path in ['TEST_of_SK_OCSP_RESPONDER_2011.pem', 'sk-ocsp-responder-certificates.pem']:
        return os.path.join(os.path.dirname(__file__), 'certs', certificate_path)

    return certificate_path
581760
private void saveCertificateFromResponse(Response response) {
        try {
            String responseBody = response.getResponseText();
            JSONObject jsonResponse = new JSONObject(responseBody);

            //handle certificate
            String certificateString = jsonResponse.getString("certificate");
            X509Certificate certificate = CertificatesUtility.base64StringToCertificate(certificateString);

            CertificatesUtility.checkValidityWithPublicKey(certificate, registrationKeyPair.getPublic());

            certificateStore.saveCertificate(registrationKeyPair, certificate);

            //save the clientId separately
            preferences.clientId.set(jsonResponse.getString("clientId"));

        } catch (Exception e) {
            throw new RuntimeException("Failed to save certificate from response", e);
        }

        logger.debug("certificate successfully saved");
    }
170970
protected Certificate loadCertificate() throws VectorPrintException {
      try {
         return CertificateHelper.loadCertificate(getValue(CERTIFICATE, URL.class).openStream());
      } catch (IOException | CertificateException ex) {
         throw new VectorPrintException(ex);
      }
   }
403017
public ArrayList<X509Certificate> getCertificateChain(PKCS7 block)
        throws IOException
    {
        X509Certificate userCert;
        userCert = block.getCertificate(certificateSerialNumber, issuerName);
        if (userCert == null)
            return null;

        ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
        certList.add(userCert);

        X509Certificate[] pkcsCerts = block.getCertificates();
        if (pkcsCerts == null
            || userCert.getSubjectDN().equals(userCert.getIssuerDN())) {
            return certList;
        }

        Principal issuer = userCert.getIssuerDN();
        int start = 0;
        while (true) {
            boolean match = false;
            int i = start;
            while (i < pkcsCerts.length) {
                if (issuer.equals(pkcsCerts[i].getSubjectDN())) {
                    // next cert in chain found
                    certList.add(pkcsCerts[i]);
                    // if selected cert is self-signed, we're done
                    // constructing the chain
                    if (pkcsCerts[i].getSubjectDN().equals(
                                            pkcsCerts[i].getIssuerDN())) {
                        start = pkcsCerts.length;
                    } else {
                        issuer = pkcsCerts[i].getIssuerDN();
                        X509Certificate tmpCert = pkcsCerts[start];
                        pkcsCerts[start] = pkcsCerts[i];
                        pkcsCerts[i] = tmpCert;
                        start++;
                    }
                    match = true;
                    break;
                } else {
                    i++;
                }
            }
            if (!match)
                break;
        }

        return certList;
    }
957904
public IOException checkCertificate() {
	SSLSocketFactory factory = context.getSocketFactory();

	try {
	    SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
	    socket.setSoTimeout(10000);
	    socket.startHandshake();
	    socket.close();
	    return null;
	}
	catch (IOException e) {
	    return e;
	}
    }
476313
def MakeCASignedCert(common_name,
                     private_key,
                     ca_cert,
                     ca_private_key,
                     serial_number=2):
  """"""
  public_key = private_key.GetPublicKey()

  builder = x509.CertificateBuilder()

  builder = builder.issuer_name(ca_cert.GetIssuer())

  subject = x509.Name(
      [x509.NameAttribute(oid.NameOID.COMMON_NAME, common_name)])
  builder = builder.subject_name(subject)

  valid_from = rdfvalue.RDFDatetime.Now() - rdfvalue.Duration("1d")
  valid_until = rdfvalue.RDFDatetime.Now() + rdfvalue.Duration("3650d")
  builder = builder.not_valid_before(valid_from.AsDatetime())
  builder = builder.not_valid_after(valid_until.AsDatetime())

  builder = builder.serial_number(serial_number)
  builder = builder.public_key(public_key.GetRawPublicKey())

  builder = builder.add_extension(
      x509.BasicConstraints(ca=False, path_length=None), critical=True)
  certificate = builder.sign(
      private_key=ca_private_key.GetRawPrivateKey(),
      algorithm=hashes.SHA256(),
      backend=openssl.backend)
  return rdf_crypto.RDFX509Cert(certificate)
93078
function saveCSR($csr, $format = self::FORMAT_PEM)
    {
        if (!is_array($csr) || !isset($csr['certificationRequestInfo'])) {
            return false;
        }

        switch (true) {
            case !($algorithm = $this->_subArray($csr, 'certificationRequestInfo/subjectPKInfo/algorithm/algorithm')):
            case is_object($csr['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey']):
                break;
            default:
                switch ($algorithm) {
                    case 'rsaEncryption':
                        $csr['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey']
                            = base64_encode("\0" . base64_decode(preg_replace('#-.+-|[\r\n]#', '', $csr['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey'])));
                        $csr['certificationRequestInfo']['subjectPKInfo']['algorithm']['parameters'] = null;
                        $csr['signatureAlgorithm']['parameters'] = null;
                        $csr['certificationRequestInfo']['signature']['parameters'] = null;
                }
        }

        $asn1 = new ASN1();

        $asn1->loadOIDs($this->oids);

        $filters = array();
        $filters['certificationRequestInfo']['subject']['rdnSequence']['value']
            = array('type' => ASN1::TYPE_UTF8_STRING);

        $asn1->loadFilters($filters);

        $this->_mapOutDNs($csr, 'certificationRequestInfo/subject/rdnSequence', $asn1);
        $this->_mapOutAttributes($csr, 'certificationRequestInfo/attributes', $asn1);
        $csr = $asn1->encodeDER($csr, $this->CertificationRequest);

        switch ($format) {
            case self::FORMAT_DER:
                return $csr;
            // case self::FORMAT_PEM:
            default:
                return "-----BEGIN CERTIFICATE REQUEST-----\r\n" . chunk_split(base64_encode($csr), 64) . '-----END CERTIFICATE REQUEST-----';
        }
    }
1325123
public function sign(CertificateSigningRequest $csr, int $serial = 0): Certificate {
        $certificate = openssl_csr_sign(
            $csr->export(),
            $this->getCertificate(),
            $this->getPrivateKey(),
            $this->getLifetime(),
            $this->getOptions(),
            $serial
        );
        return new Certificate($certificate);
    }
177324
public static void setVerificationHeaders(HttpServletResponse response, File file)
  throws IOException {
    response.setHeader(TransferFsImage.CONTENT_LENGTH,
        String.valueOf(file.length()));
    MD5Hash hash = MD5FileUtils.readStoredMd5ForFile(file);
    if (hash != null) {
      response.setHeader(TransferFsImage.MD5_HEADER, hash.toString());
    }
  }
627775
public static Certificate readCertificate(String type, InputStream in) {
		try {
			return getCertificateFactory(type).generateCertificate(in);
		} catch (CertificateException e) {
			throw new CryptoException(e);
		}
	}
129071
private static java.security.cert.Certificate[] mapSignersToCertArray(
        CodeSigner[] signers) {

        if (signers != null) {
            ArrayList certChains = new ArrayList();
            for (int i = 0; i < signers.length; i++) {
                certChains.addAll(
                    signers[i].getSignerCertPath().getCertificates());
            }

            // Convert into a Certificate[]
            return (java.security.cert.Certificate[])
                certChains.toArray(
                    new java.security.cert.Certificate[certChains.size()]);
        }
        return null;
    }
871881
public function selfSign(CertificateSigningRequest $csr, int $serial = 0): Certificate {
        $certificate = openssl_csr_sign(
            $csr->export(),
            NULL,
            $this->getPrivateKey(),
            $this->getLifetime(),
            $this->getOptions(),
            $serial
        );
        return new Certificate($certificate);
    }
963858
public Certificate getMatchingCert(TLSARecord tlsaRecord, List<Certificate> certs) {

        for (Certificate cert : certs) {

            byte[] digestMatch = new byte[0];
            byte[] selectorData = new byte[0];

            try {
                // Get Selector Value
                switch (tlsaRecord.getSelector()) {
                    case TLSARecord.Selector.FULL_CERTIFICATE:
                        selectorData = cert.getEncoded();
                        break;

                    case TLSARecord.Selector.SUBJECT_PUBLIC_KEY_INFO:
                        selectorData = cert.getPublicKey().getEncoded();
                        break;
                }

                // Validate Matching Type
                switch (tlsaRecord.getMatchingType()) {
                    case TLSARecord.MatchingType.EXACT:
                        digestMatch = selectorData;
                        break;
                    case TLSARecord.MatchingType.SHA256:
                        digestMatch = MessageDigest.getInstance("SHA-256").digest(selectorData);
                        break;
                    case TLSARecord.MatchingType.SHA512:
                        digestMatch = MessageDigest.getInstance("SHA-512").digest(selectorData);
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (Arrays.equals(digestMatch, tlsaRecord.getCertificateAssociationData())) {
                return cert;
            }
        }

        return null;
    }
74621
@Override
	public Certificate engineGetCertificate(String s) {
		ResourceTrustAnchor trustAnchor = getCertificateEntry(s);
		if (trustAnchor != null) {
			try {
				return trustAnchor.getTrustAnchor().getTrustedCert();
			} catch (ResourceStoreException e) {
				return null;
			}
		}
		return null;
	}
749339
public TLSCertificateKeyPair serverCert(String subjectAlternativeName) {
        try {
            return createCert(CertType.SERVER, subjectAlternativeName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }