Returns a X509 binary certificate for a given domain name if a certificate has been generated for it

@param locale
@param model
@param response
@param hostname
@throws Exception
351627
@RequestMapping(value = "/cert/{hostname:.+}", method = {RequestMethod.GET, RequestMethod.HEAD})
    public
    @ResponseBody
    void getCert(Locale locale, Model model, HttpServletResponse response, @PathVariable String hostname) throws Exception {
        // Set the appropriate headers so the browser thinks this is a file
        response.reset();
        response.setContentType("application/x-x509-ca-cert");
        response.setHeader("Content-Disposition", "attachment;filename=" + hostname + ".cer");

        // special handling for hostname=="root"
        // return the CyberVillians Root Cert in this case
        if (hostname.equals("root")) {
            hostname = "cybervillainsCA";
            response.setContentType("application/pkix-cert ");
        }

        // get the cert for the hostname
        KeyStoreManager keyStoreManager = com.groupon.odo.bmp.Utils.getKeyStoreManager(hostname);

        if (hostname.equals("cybervillainsCA")) {
            // get the cybervillians cert from resources
            File root = new File("seleniumSslSupport" + File.separator + hostname);

            // return the root cert
            Files.copy(new File(root.getAbsolutePath() + File.separator + hostname + ".cer").toPath(), response.getOutputStream());
            response.flushBuffer();
        } else {
            // return the cert for the appropriate alias
            response.getOutputStream().write(keyStoreManager.getCertificateByAlias(hostname).getEncoded());
            response.flushBuffer();
        }


    }
1355178
public static java.security.cert.X509Certificate convert(javax.security.cert.X509Certificate cert) {
        try {
            byte[] encoded = cert.getEncoded();
            ByteArrayInputStream bis = new ByteArrayInputStream(encoded);
            java.security.cert.CertificateFactory cf
                = java.security.cert.CertificateFactory.getInstance("X.509");
            return (java.security.cert.X509Certificate)cf.generateCertificate(bis);
        } catch (java.security.cert.CertificateEncodingException e) {
        } catch (javax.security.cert.CertificateEncodingException e) {
        } catch (java.security.cert.CertificateException e) {
        }
        return null;
    }
620198
@Override
    @SuppressWarnings("StringEquality")
    public Object getField(String name) throws UnresolvedException{
        if(name=="protocol")
            return getSession().getProtocol();
        else if(name=="cipher")
            return getSession().getCipherSuite();
        else if(name=="local")
            return new CertificateBean((X509Certificate)getSession().getLocalCertificates()[0]);
        else if(name=="peer"){
            try{
                return new CertificateBean((X509Certificate)getSession().getPeerCertificates()[0]);
            }catch(SSLPeerUnverifiedException ex){
                return null;
            }
        }else
            throw new UnresolvedException(name);
    }
1286016
public static wisite_translationinternalip_binding[] get(nitro_service service, String sitepath) throws Exception{
		wisite_translationinternalip_binding obj = new wisite_translationinternalip_binding();
		obj.set_sitepath(sitepath);
		wisite_translationinternalip_binding response[] = (wisite_translationinternalip_binding[]) obj.get_resources(service);
		return response;
	}
584431
private Certificate generateCertificate()
            throws IOException, CertificateException {
        InputStream caInput = null;
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            caInput = new ByteArrayInputStream(caCertificate.getBytes("UTF-8"));
            return cf.generateCertificate(caInput);
        } finally {
            IOUtil.closeResource(caInput);
        }
    }
349668
public static RevocationStatus check(X509Certificate cert,
                                         X509Certificate issuerCert,
                                         URI responderURI,
                                         X509Certificate responderCert,
                                         Date date, List<Extension> extensions)
        throws IOException, CertPathValidatorException
    {
        CertId certId = null;
        try {
            X509CertImpl certImpl = X509CertImpl.toImpl(cert);
            certId = new CertId(issuerCert, certImpl.getSerialNumberObject());
        } catch (CertificateException | IOException e) {
            throw new CertPathValidatorException
                ("Exception while encoding OCSPRequest", e);
        }
        OCSPResponse ocspResponse = check(Collections.singletonList(certId),
            responderURI, issuerCert, responderCert, date, extensions);
        return (RevocationStatus) ocspResponse.getSingleResponse(certId);
    }
322501
public static dnsglobal_binding get(nitro_service service) throws Exception{
		dnsglobal_binding obj = new dnsglobal_binding();
		dnsglobal_binding response = (dnsglobal_binding) obj.get_resource(service);
		return response;
	}
307473
public static sslpolicy get(nitro_service service, String name) throws Exception{
		sslpolicy obj = new sslpolicy();
		obj.set_name(name);
		sslpolicy response = (sslpolicy) obj.get_resource(service);
		return response;
	}
442186
public static sslcertkey[] get(nitro_service service) throws Exception{
		sslcertkey obj = new sslcertkey();
		sslcertkey[] response = (sslcertkey[])obj.get_resources(service);
		return response;
	}
906698
private boolean verifyHostname(String hostname, X509Certificate certificate) {
        hostname = hostname.toLowerCase(Locale.US);
        boolean hasDns = false;
        List<String> altNames = getSubjectAltNames(certificate, ALT_DNS_NAME);
        for (int i = 0, size = altNames.size(); i < size; i++) {
            hasDns = true;
            if (verifyHostname(hostname, altNames.get(i))) {
                return true;
            }
        }

        if (!hasDns) {
            X500Principal principal = certificate.getSubjectX500Principal();
            // RFC 2818 advises using the most specific name for matching.
            String cn = new DistinguishedNameParser(principal).findMostSpecific("cn");
            if (cn != null) {
                return verifyHostname(hostname, cn);
            }
            else {
                // NOTE: In case of empty Common Name (CN), not checking
                return true;
            }
        }

        return false;
    }
964279
public static String getIdentity(X509Certificate cert) {
    	if (cert == null) {
    		return null;
    	}

    	String subjectDN = cert.getSubjectX500Principal().getName(X500Principal.RFC2253);
    	X509Name name = new X509Name(true, subjectDN);
	    return X509NameHelper.toString(name);
    }
654279
private static X500Principal getX500Principal(X509Certificate cert,
            boolean getIssuer) throws Exception {
        byte[] encoded = cert.getEncoded();
        DerInputStream derIn = new DerInputStream(encoded);
        DerValue tbsCert = derIn.getSequence(3)[0];
        DerInputStream tbsIn = tbsCert.data;
        DerValue tmp;
        tmp = tbsIn.getDerValue();
        // skip version number if present
        if (tmp.isContextSpecific((byte)0)) {
          tmp = tbsIn.getDerValue();
        }
        // tmp always contains serial number now
        tmp = tbsIn.getDerValue();              // skip signature
        tmp = tbsIn.getDerValue();              // issuer
        if (getIssuer == false) {
            tmp = tbsIn.getDerValue();          // skip validity
            tmp = tbsIn.getDerValue();          // subject
        }
        byte[] principalBytes = tmp.toByteArray();
        return new X500Principal(principalBytes);
    }
905572
public boolean verifyHostname(String hostname, String pattern) {
        // Basic sanity checks
        // Check length == 0 instead of .isEmpty() to support Java 5.
        if ((hostname == null) || (hostname.length() == 0) || (hostname.startsWith("."))
            || (hostname.endsWith(".."))) {
            // Invalid domain name
            return false;
        }
        if ((pattern == null) || (pattern.length() == 0) || (pattern.startsWith("."))
            || (pattern.endsWith(".."))) {
            // Invalid pattern/domain name
            return false;
        }

        // Normalize hostname and pattern by turning them into absolute domain names if they are not
        // yet absolute. This is needed because server certificates do not normally contain absolute
        // names or patterns, but they should be treated as absolute. At the same time, any hostname
        // presented to this method should also be treated as absolute for the purposes of matching
        // to the server certificate.
        //   www.android.com  matches www.android.com
        //   www.android.com  matches www.android.com.
        //   www.android.com. matches www.android.com.
        //   www.android.com. matches www.android.com
        if (!hostname.endsWith(".")) {
            hostname += '.';
        }
        if (!pattern.endsWith(".")) {
            pattern += '.';
        }
        // hostname and pattern are now absolute domain names.

        pattern = pattern.toLowerCase(Locale.US);
        // hostname and pattern are now in lower case -- domain names are case-insensitive.

        if (!pattern.contains("*")) {
            // Not a wildcard pattern -- hostname and pattern must match exactly.
            return hostname.equals(pattern);
        }
        // Wildcard pattern

        // WILDCARD PATTERN RULES:
        // 1. Asterisk (*) is only permitted in the left-most domain name label and must be the
        //    only character in that label (i.e., must match the whole left-most label).
        //    For example, *.example.com is permitted, while *a.example.com, a*.example.com,
        //    a*b.example.com, a.*.example.com are not permitted.
        // 2. Asterisk (*) cannot match across domain name labels.
        //    For example, *.example.com matches test.example.com but does not match
        //    sub.test.example.com.
        // 3. Wildcard patterns for single-label domain names are not permitted.

        if ((!pattern.startsWith("*.")) || (pattern.indexOf('*', 1) != -1)) {
            // Asterisk (*) is only permitted in the left-most domain name label and must be the only
            // character in that label
            return false;
        }

        // Optimization: check whether hostname is too short to match the pattern. hostName must be at
        // least as long as the pattern because asterisk must match the whole left-most label and
        // hostname starts with a non-empty label. Thus, asterisk has to match one or more characters.
        if (hostname.length() < pattern.length()) {
            // hostname too short to match the pattern.
            return false;
        }

        if ("*.".equals(pattern)) {
            // Wildcard pattern for single-label domain name -- not permitted.
            return false;
        }

        // hostname must end with the region of pattern following the asterisk.
        String suffix = pattern.substring(1);
        if (!hostname.endsWith(suffix)) {
            // hostname does not end with the suffix
            return false;
        }

        // Check that asterisk did not match across domain name labels.
        int suffixStartIndexInHostname = hostname.length() - suffix.length();
        return (suffixStartIndexInHostname <= 0)
            || (hostname.lastIndexOf('.', suffixStartIndexInHostname - 1) == -1);
    }
1145140
private X509Certificate loadX509FromPEMFile(String filename) {
        try {
            return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(FileReader.openStreamToFileFromClassPathOrPath(filename));
        } catch (Exception e) {
            throw new RuntimeException("Exception reading X509 from PEM file", e);
        }
    }
262249
public static javax.security.cert.X509Certificate convert(java.security.cert.X509Certificate cert) {
        try {
            byte[] encoded = cert.getEncoded();
            return javax.security.cert.X509Certificate.getInstance(encoded);
        } catch (java.security.cert.CertificateEncodingException e) {
        } catch (javax.security.cert.CertificateEncodingException e) {
        } catch (javax.security.cert.CertificateException e) {
        }
        return null;
    }
1212328
private CertificateAuthenticator getCertificateAuthenticator(X509Certificate[] certChain) throws LoginException {
        CertificateAuthenticator certAuthen = null;
        ConcurrentServiceReferenceMap<String, CertificateAuthenticator> certAuthens = JAASServiceImpl.getCertificateAuthenticators();
        Set<String> keys = certAuthens.keySet();
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "CertificateAuthenticator keys:", keys);
        }
        // Iterate through the CertificateAuthenticators and call
        // authenticateCertificateChain. Return the 1st one to return true.
        for (String key : keys) {
            CertificateAuthenticator current = certAuthens.getService(key);
            if (current.authenticateCertificateChain(certChain)) {
                certAuthen = current;
                break;
            }
        }
        return certAuthen;
    }
623935
public static sslcertkey[] get(nitro_service service, String certkey[]) throws Exception{
		if (certkey !=null && certkey.length>0) {
			sslcertkey response[] = new sslcertkey[certkey.length];
			sslcertkey obj[] = new sslcertkey[certkey.length];
			for (int i=0;i<certkey.length;i++) {
				obj[i] = new sslcertkey();
				obj[i].set_certkey(certkey[i]);
				response[i] = (sslcertkey) obj[i].get_resource(service);
			}
			return response;
		}
		return null;
	}