/*
Make sure there's a start line with '-----BEGIN CERTIFICATE-----'
and end line with '-----END CERTIFICATE-----', so as to be compliant
with x509 parsers
507276
function normalizeX509(raw, loggerPrefix) {
    logger.debug(`${loggerPrefix} [normalizeX509] raw cert: ${raw}`);
    const regex = /(\-\-\-\-\-\s*BEGIN ?[^-]+?\-\-\-\-\-)([\s\S]*)(\-\-\-\-\-\s*END ?[^-]+?\-\-\-\-\-)/;
    let matches = raw.match(regex);
    if (!matches || matches.length !== 4) {
        throw new Error('Failed to find start line or end line of the certificate.');
    }

    // remove the first element that is the whole match
    matches.shift();
    // remove LF or CR
    matches = matches.map((element) => {
        return element.trim();
    });

    // make sure '-----BEGIN CERTIFICATE-----' and '-----END CERTIFICATE-----' are in their own lines
    // and that it ends in a new line
    return matches.join('\n') + '\n';
}
157993
private void verifyCert(X500Name subject,
        CertificateExtensions extensions)
        throws CertificateParsingException, IOException {

        // if SubjectName is empty, check for SubjectAlternativeNameExtension
        if (subject.isEmpty()) {
            if (extensions == null) {
                throw new CertificateParsingException("X.509 Certificate is " +
                        "incomplete: subject field is empty, and certificate " +
                        "has no extensions");
            }
            SubjectAlternativeNameExtension subjectAltNameExt = null;
            SubjectAlternativeNameExtension extValue = null;
            GeneralNames names = null;
            try {
                subjectAltNameExt = (SubjectAlternativeNameExtension)
                        extensions.get(SubjectAlternativeNameExtension.NAME);
                names = subjectAltNameExt.get(
                        SubjectAlternativeNameExtension.SUBJECT_NAME);
            } catch (IOException e) {
                throw new CertificateParsingException("X.509 Certificate is " +
                        "incomplete: subject field is empty, and " +
                        "SubjectAlternativeName extension is absent");
            }

            // SubjectAlternativeName extension is empty or not marked critical
            if (names == null || names.isEmpty()) {
                throw new CertificateParsingException("X.509 Certificate is " +
                        "incomplete: subject field is empty, and " +
                        "SubjectAlternativeName extension is empty");
            } else if (subjectAltNameExt.isCritical() == false) {
                throw new CertificateParsingException("X.509 Certificate is " +
                        "incomplete: SubjectAlternativeName extension MUST " +
                        "be marked critical when subject field is empty");
            }
        }
    }
186073
private X509Certificate []getClientCertificatesImpl()
    throws CertificateException
  {
    if (! (_s instanceof SSLSocket))
      return null;
    
    SSLSocket sslSocket = (SSLSocket) _s;

    SSLSession sslSession = sslSocket.getSession();
    if (sslSession == null)
      return null;

    try {
      return (X509Certificate []) sslSession.getPeerCertificates();
    } catch (SSLPeerUnverifiedException e) {
      if (log.isLoggable(Level.FINEST))
        log.log(Level.FINEST, e.toString(), e);
      
      return null;
    } catch (Throwable e) {
      log.log(Level.FINER, e.toString(), e);
    }
    
    return null;
  }
733655
function processLines(begin, end) {
      var lines = ''
      var s = '';
      end -= 1;
      if (begin < end) {
//        console.log(begin, end);
        var src = sources[scope.name];
        lines = src.slice(begin, end);
        while (lines.length > 0 && lines[0] == '')
          lines = lines.slice(1, lines.length);
        if (lines.length > 0) // && !(lines.length == 1 && lines[0] == ''))
        {
          var s1 = lines.join('\n');
//          s1 = s1.replace(/\</g, "&lt;").replace(/\>/g, "&gt;");
          s += '<pre style="padding-left: 50px; display: none;"><code  class="language-'+scope.extlang+'" data-nodes="show" data-code="hide">'+htmlEscape(s1)+'</code></pre>' //prism
        }
//          s += '<pre style="padding-left: 50px;"><code>'+lines.join('\n')+'</code></pre>'
      }
      // EXECUTOR.HOOK: afterProcessLines [
      s = executor.hook('afterProcessLines', s, [sources, scope, begin, end, lines])
      // EXECUTOR.HOOK: afterProcessLines ]

      return s;
    }
104978
public static void verify(X509Certificate cert, PublicKey key,
            Provider sigProvider) throws CertificateException,
            NoSuchAlgorithmException, InvalidKeyException, SignatureException {
        cert.verify(key, sigProvider);
    }
116383
private void disableStrictSSL() {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };

        // Ignore differences between given hostname and certificate hostname
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(hv);
        } catch (Exception e) {
        }
    }
766132
static void verifyCAKeyUsage(X509Certificate cert)
            throws CertPathValidatorException {
        String msg = "CA key usage";
        if (debug != null) {
            debug.println("KeyChecker.verifyCAKeyUsage() ---checking " + msg
                          + "...");
        }

        boolean[] keyUsageBits = cert.getKeyUsage();

        // getKeyUsage returns null if the KeyUsage extension is not present
        // in the certificate - in which case there is nothing to check
        if (keyUsageBits == null) {
            return;
        }

        // throw an exception if the keyCertSign bit is not set
        if (!keyUsageBits[KEY_CERT_SIGN]) {
            throw new CertPathValidatorException
                (msg + " check failed: keyCertSign bit is not set", null,
                 null, -1, PKIXReason.INVALID_KEY_USAGE);
        }

        if (debug != null) {
            debug.println("KeyChecker.verifyCAKeyUsage() " + msg
                          + " verified.");
        }
    }
114957
public static X509CertImpl toImpl(X509Certificate cert)
            throws CertificateException {
        if (cert instanceof X509CertImpl) {
            return (X509CertImpl)cert;
        } else {
            return X509Factory.intern(cert);
        }
    }
100320
function (context, run, done) {
        var request,
            pfxPath,
            keyPath,
            certPath,
            fileResolver,

            certificate;

        // A. Check if we have the file resolver
        fileResolver = run.options.fileResolver;

        if (!fileResolver) { return done(); } // No point going ahead

        // B. Ensure we have the request
        request = _.get(context.item, 'request');
        if (!request) { return done(new Error('No request to resolve certificates for.')); }

        // C. See if any cert should be sent, by performing a URL matching
        certificate = run.options.certificates && run.options.certificates.resolveOne(request.url);
        if (!certificate) { return done(); }

        // D. Fetch the paths
        // @todo: check why aren't we reading ca file (why are we not supporting ca file)
        pfxPath = _.get(certificate, 'pfx.src');
        keyPath = _.get(certificate, 'key.src');
        certPath = _.get(certificate, 'cert.src');

        // E. Read from the path, and add the values to the certificate, also associate
        // the certificate with the current request.
        async.mapValues({
            pfx: pfxPath,
            key: keyPath,
            cert: certPath
        }, function (value, key, next) {
            // bail out if value is not defined
            // @todo add test with server which only accepts cert file
            if (!value) { return next(); }

            // eslint-disable-next-line security/detect-non-literal-fs-filename
            fileResolver.readFile(value, function (err, data) {
                // Swallow the error after triggering a warning message for the user.
                err && run.triggers.console(context.coords, 'warn',
                    `certificate "${key}" load error:  ${(err.message || err)}`);
                next(null, data);
            });
        }, function (err, fileContents) {
            if (err) {
                // Swallow the error after triggering a warning message for the user.
                run.triggers.console(context.coords, 'warn', 'certificate load error: ' + (err.message || err));

                return done();
            }

            if (fileContents) {
                !_.isNil(fileContents.pfx) && _.set(certificate, 'pfx.value', fileContents.pfx);
                !_.isNil(fileContents.key) && _.set(certificate, 'key.value', fileContents.key);
                !_.isNil(fileContents.cert) && _.set(certificate, 'cert.value', fileContents.cert);

                (fileContents.cert || fileContents.key || fileContents.pfx) && (request.certificate = certificate);
            }
            done();
        });
    }
351351
public static void verifyAndThrow(final String name, final X509Certificate cert) throws CertificateException{
		if (!verify(name, cert)) {
			throw new CertificateException("No name matching " + name + " found");
		}		
	}
264035
private void matchEndLine() {
		// First, parse all whitespace characters except for new lines
		index = skipLineSpace(index);

		// Second, check whether we've reached the end-of-file (as signaled by
		// running out of tokens), or we've encountered some token which not a
		// newline.
		if (index >= tokens.size()) {
			return; // EOF
		} else if (tokens.get(index).kind != NewLine) {
			syntaxError("expected end-of-line", tokens.get(index));
		} else {
			index = index + 1;
		}
	}
155790
private void checkPair() throws CertificateException {

        /* if either of pair is missing, return w/o error */
        if (forward == null || reverse == null) {
            return;
        }
        /*
         * If both elements of the pair are present, check that they
         * are a valid pair.
         */
        X500Principal fwSubject = forward.getSubjectX500Principal();
        X500Principal fwIssuer = forward.getIssuerX500Principal();
        X500Principal rvSubject = reverse.getSubjectX500Principal();
        X500Principal rvIssuer = reverse.getIssuerX500Principal();
        if (!fwIssuer.equals(rvSubject) || !rvIssuer.equals(fwSubject)) {
            throw new CertificateException("subject and issuer names in "
                + "forward and reverse certificates do not match");
        }

        /* check signatures unless key parameters are missing */
        try {
            PublicKey pk = reverse.getPublicKey();
            if (!(pk instanceof DSAPublicKey) ||
                        ((DSAPublicKey)pk).getParams() != null) {
                forward.verify(pk);
            }
            pk = forward.getPublicKey();
            if (!(pk instanceof DSAPublicKey) ||
                        ((DSAPublicKey)pk).getParams() != null) {
                reverse.verify(pk);
            }
        } catch (GeneralSecurityException e) {
            throw new CertificateException("invalid signature: "
                + e.getMessage());
        }
    }
222548
private String getCertCN(X509Certificate x509)
        throws CertificateParsingException {

        X500Principal principal = x509.getSubjectX500Principal();
        String subjectName = principal.getName();

        String[] fields = subjectName.split(",");
        for (String field : fields) {
            if (field.startsWith("CN=")) {
                String serverName = field.substring(3);
                return serverName.toLowerCase();
            }
        }

        throw new CertificateParsingException("Certificate CN not found");
    }
504480
public void validate(KeyStore keyStore, Certificate cert) throws CertificateException
{
    Certificate[] certChain = null;
    
    if (cert != null && cert instanceof X509Certificate)
    {
        ((X509Certificate)cert).checkValidity();
        
        String certAlias = null;
        try
        {
            if (keyStore == null)
            {
                throw new InvalidParameterException("Keystore cannot be null");
            }

            certAlias = keyStore.getCertificateAlias((X509Certificate)cert);
            if (certAlias == null)
            {
                certAlias = "JETTY" + String.format("%016X",__aliasCount.incrementAndGet());
                keyStore.setCertificateEntry(certAlias, cert);
            }
            
            certChain = keyStore.getCertificateChain(certAlias);
            if (certChain == null || certChain.length == 0)
            {
                throw new IllegalStateException("Unable to retrieve certificate chain");
            }
        }
        catch (KeyStoreException kse)
        {
            LOG.error("Error while valid keystore", kse);
            throw new CertificateException("Unable to validate certificate" +
                    (certAlias == null ? "":" for alias [" +certAlias + "]") + ": " + kse.getMessage(), kse);
        }
        
        validate(certChain);
    } 
}
94569
def process_ldiff(self, data, name):
        
        from cryptography.x509.base import load_der_x509_certificate
        reg = re.compile(r'binary::\s*([0-9a-zA-Z+/=\s\t\r\n]{20,})$', re.MULTILINE | re.DOTALL)
        matches = re.findall(reg, str(data))

        ret = []
        num_certs_found = 0
        for idx, match in enumerate(matches):
            match = re.sub('[\r\t\n\s]', '', match)
            try:
                bindata = base64.b64decode(match)
                x509 = load_der_x509_certificate(bindata, self.get_backend())

                self.num_ldiff_cert += 1
                sub = self.process_x509(x509, name=name, pem=False, source='ldiff-cert')
                ret.append(sub)

            except Exception as e:
                logger.debug('Error in line ldiff file processing %s, idx %s, matchlen %s : %s'
                             % (name, idx, len(match), e))
                self.trace_logger.log(e)
        return ret
625444
function loadX509($cert)
    {
        if (is_array($cert) && isset($cert['tbsCertificate'])) {
            $this->currentCert = $cert;
            unset($this->signatureSubject);
            return false;
        }

        $asn1 = new File_ASN1();

        /*
            X.509 certs are assumed to be base64 encoded but sometimes they'll have additional things in them above and beyond the ceritificate. ie.
            some may have the following preceeding the -----BEGIN CERTIFICATE----- line:

            subject=/O=organization/OU=org unit/CN=common name
            issuer=/O=organization/CN=common name
        */
        $temp = preg_replace('#^(?:[^-].+[\r\n]+)+|-.+-|[\r\n]| #', '', $cert);
        $temp = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $temp) ? base64_decode($temp) : false;
        if ($temp != false) {
            $cert = $temp;
        }

        if ($cert === false) {
            $this->currentCert = false;
            return false;
        }

        $asn1->loadOIDs($this->oids);
        $decoded = $asn1->decodeBER($cert);

        if (!empty($decoded)) {
            $x509 = $asn1->asn1map($decoded[0], $this->Certificate);
        }
        if (!isset($x509) || $x509 === false) {
            $this->currentCert = false;
            return false;
        }

        $this->signatureSubject = substr($cert, $decoded[0]['content'][0]['start'], $decoded[0]['content'][0]['length']);

        $this->_mapInExtensions($x509, 'tbsCertificate/extensions', $asn1);

        $key = &$x509['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'];
        $key = $this->_reformatKey($x509['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['algorithm'], $key);

        $this->currentCert = $x509;
        $this->dn = $x509['tbsCertificate']['subject'];

        $currentKeyIdentifier = $this->getExtension('id-ce-subjectKeyIdentifier');
        $this->currentKeyIdentifier = is_string($currentKeyIdentifier) ? $currentKeyIdentifier : NULL;

        return $x509;
    }
601887
private void checkBasicConstraints(X509Certificate currCert)
        throws CertPathValidatorException
    {
        String msg = "basic constraints";
        if (debug != null) {
            debug.println("---checking " + msg + "...");
            debug.println("i = " + i +
                        ", maxPathLength = " + maxPathLength);
        }

        /* check if intermediate cert */
        if (i < certPathLength) {
            // RFC5280: If certificate i is a version 3 certificate, verify
            // that the basicConstraints extension is present and that cA is
            // set to TRUE.  (If certificate i is a version 1 or version 2
            // certificate, then the application MUST either verify that
            // certificate i is a CA certificate through out-of-band means
            // or reject the certificate.  Conforming implementations may
            // choose to reject all version 1 and version 2 intermediate
            // certificates.)
            //
            // We choose to reject all version 1 and version 2 intermediate
            // certificates except that it is self issued by the trust
            // anchor in order to support key rollover or changes in
            // certificate policies.
            int pathLenConstraint = -1;
            if (currCert.getVersion() < 3) {    // version 1 or version 2
                if (i == 1) {                   // issued by a trust anchor
                    if (X509CertImpl.isSelfIssued(currCert)) {
                        pathLenConstraint = Integer.MAX_VALUE;
                    }
                }
            } else {
                pathLenConstraint = currCert.getBasicConstraints();
            }

            if (pathLenConstraint == -1) {
                throw new CertPathValidatorException
                    (msg + " check failed: this is not a CA certificate",
                     null, null, -1, PKIXReason.NOT_CA_CERT);
            }

            if (!X509CertImpl.isSelfIssued(currCert)) {
                if (maxPathLength <= 0) {
                   throw new CertPathValidatorException
                        (msg + " check failed: pathLenConstraint violated - "
                         + "this cert must be the last cert in the "
                         + "certification path", null, null, -1,
                         PKIXReason.PATH_TOO_LONG);
                }
                maxPathLength--;
            }
            if (pathLenConstraint < maxPathLength)
                maxPathLength = pathLenConstraint;
        }

        if (debug != null) {
            debug.println("after processing, maxPathLength = " + maxPathLength);
            debug.println(msg + " verified.");
        }
    }