Example usage for java.security.cert Certificate getEncoded

List of usage examples for java.security.cert Certificate getEncoded

Introduction

In this page you can find the example usage for java.security.cert Certificate getEncoded.

Prototype

public abstract byte[] getEncoded() throws CertificateEncodingException;

Source Link

Document

Returns the encoded form of this certificate.

Usage

From source file:org.cesecore.util.CertTools.java

/**
 * Generate SHA1 fingerprint of certificate in string representation.
 * //from ww  w.j a  va2s .  c o  m
 * @param cert Certificate.
 * 
 * @return String containing hex format of SHA1 fingerprint (lower case), or null if input is null.
 */
public static String getFingerprintAsString(Certificate cert) {
    if (cert == null) {
        return null;
    }
    try {
        byte[] res = generateSHA1Fingerprint(cert.getEncoded());

        return new String(Hex.encode(res));
    } catch (CertificateEncodingException cee) {
        log.error("Error encoding certificate.", cee);
    }

    return null;
}

From source file:org.cesecore.util.CertTools.java

/**
 * Dumps a certificate (cvc or x.509) to string format, suitable for manual inspection/debugging.
 * //w  ww  .  ja  v  a2 s .co  m
 * @param cert Certificate
 * 
 * @return String with cvc or asn.1 dump.
 */
public static String dumpCertificateAsString(final Certificate cert) {
    String ret = null;
    if (cert instanceof X509Certificate) {
        try {
            final Certificate c = getCertfromByteArray(cert.getEncoded());
            ret = c.toString();
            // ASN1InputStream ais = new ASN1InputStream(new ByteArrayInputStream(cert.getEncoded()));
            // ASN1Primitive obj = ais.readObject();
            // ret = ASN1Dump.dumpAsString(obj);
        } catch (CertificateException e) {
            ret = e.getMessage();
        }
    } else if (StringUtils.equals(cert.getType(), "CVC")) {
        final CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert;
        final CVCObject obj = cvccert.getCVCertificate();
        ret = obj.getAsText("");
    } else {
        throw new IllegalArgumentException(
                "dumpCertificateAsString: Certificate of type " + cert.getType() + " is not implemented");
    }
    return ret;
}

From source file:org.ejbca.ui.web.admin.cainterface.CACertReqServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse res)
        throws java.io.IOException, ServletException {
    log.trace(">doGet()");

    // Check if authorized
    EjbcaWebBean ejbcawebbean = (EjbcaWebBean) req.getSession().getAttribute("ejbcawebbean");
    if (ejbcawebbean == null) {
        try {/*www  . java  2s  .  c  om*/
            ejbcawebbean = (EjbcaWebBean) java.beans.Beans
                    .instantiate(Thread.currentThread().getContextClassLoader(), EjbcaWebBean.class.getName());
        } catch (ClassNotFoundException exc) {
            throw new ServletException(exc.getMessage());
        } catch (Exception exc) {
            throw new ServletException(" Cannot create bean of class " + EjbcaWebBean.class.getName(), exc);
        }
        req.getSession().setAttribute("ejbcawebbean", ejbcawebbean);
    }

    // Check if authorized
    CAInterfaceBean cabean = (CAInterfaceBean) req.getSession().getAttribute("cabean");
    if (cabean == null) {
        try {
            cabean = (CAInterfaceBean) java.beans.Beans.instantiate(
                    Thread.currentThread().getContextClassLoader(), CAInterfaceBean.class.getName());
        } catch (ClassNotFoundException exc) {
            throw new ServletException(exc.getMessage());
        } catch (Exception exc) {
            throw new ServletException(" Cannot create bean of class " + CAInterfaceBean.class.getName(), exc);
        }
        req.getSession().setAttribute("cabean", cabean);
    }

    try {
        ejbcawebbean.initialize(req, StandardRules.ROLE_ROOT.resource());
    } catch (Exception e) {
        throw new java.io.IOException("Authorization Denied");
    }

    try {
        cabean.initialize(ejbcawebbean);
    } catch (Exception e) {
        throw new java.io.IOException("Error initializing CACertReqServlet");
    }

    // Keep this for logging.
    String remoteAddr = req.getRemoteAddr();
    RequestHelper.setDefaultCharacterEncoding(req);
    String command = req.getParameter(COMMAND_PROPERTY_NAME);
    String format = req.getParameter(FORMAT_PROPERTY_NAME);
    if (command == null) {
        command = "";
    }
    if (command.equalsIgnoreCase(COMMAND_CERTREQ)) {
        try {
            byte[] request = cabean.getRequestData();
            String filename = null;
            CVCertificate cvccert = null;
            boolean isx509cert = false;
            try {
                CVCObject parsedObject = CertificateParser.parseCVCObject(request);
                // We will handle both the case if the request is an
                // authenticated request, i.e. with an outer signature
                // and when the request is missing the (optional) outer
                // signature.
                if (parsedObject instanceof CVCAuthenticatedRequest) {
                    CVCAuthenticatedRequest cvcreq = (CVCAuthenticatedRequest) parsedObject;
                    cvccert = cvcreq.getRequest();
                } else {
                    cvccert = (CVCertificate) parsedObject;
                }
                HolderReferenceField chrf = cvccert.getCertificateBody().getHolderReference();
                if (chrf != null) {
                    filename = chrf.getConcatenated();
                }
            } catch (ParseException ex) {
                // Apparently it wasn't a CVC certificate, was it a certificate request?
                try {
                    PKCS10RequestMessage p10 = RequestMessageUtils.genPKCS10RequestMessage(request);
                    filename = CertTools.getPartFromDN(p10.getRequestX500Name().toString(), "CN") + "_csr";
                } catch (Exception e) { // NOPMD
                    // Nope, not a certificate request either, see if it was an X.509 certificate
                    Certificate cert = CertTools.getCertfromByteArray(request);
                    filename = CertTools.getPartFromDN(CertTools.getSubjectDN(cert), "CN");
                    if (filename == null) {
                        filename = "cert";
                    }
                    isx509cert = true;
                }
            }

            int length = request.length;
            byte[] outbytes = request;
            if (!StringUtils.equals(format, "binary")) {
                String begin = RequestHelper.BEGIN_CERTIFICATE_REQUEST_WITH_NL;
                String end = RequestHelper.END_CERTIFICATE_REQUEST_WITH_NL;
                if (isx509cert) {
                    begin = RequestHelper.BEGIN_CERTIFICATE_WITH_NL;
                    end = RequestHelper.END_CERTIFICATE_WITH_NL;
                }
                byte[] b64certreq = Base64.encode(request);
                String out = begin;
                out += new String(b64certreq);
                out += end;
                length = out.length();
                filename += ".pem";
                outbytes = out.getBytes();
            } else if (cvccert != null) {
                filename += ".cvreq";
            } else {
                if (isx509cert) {
                    filename += ".crt";
                } else {
                    filename += ".req";
                }
            }

            // We must remove cache headers for IE
            ServletUtils.removeCacheHeaders(res);
            res.setHeader("Content-disposition",
                    "attachment; filename=\"" + StringTools.stripFilename(filename) + "\"");
            res.setContentType("application/octet-stream");
            res.setContentLength(length);
            res.getOutputStream().write(outbytes);
            String iMsg = intres.getLocalizedMessage("certreq.sentlatestcertreq", remoteAddr);
            log.info(iMsg);
        } catch (Exception e) {
            String errMsg = intres.getLocalizedMessage("certreq.errorsendlatestcertreq", remoteAddr);
            log.error(errMsg, e);
            res.sendError(HttpServletResponse.SC_NOT_FOUND, errMsg);
            return;
        }
    }
    if (command.equalsIgnoreCase(COMMAND_CERT)) {
        try {
            Certificate cert = cabean.getProcessedCertificate();
            if (!StringUtils.equals(format, "binary")) {
                byte[] b64cert = Base64.encode(cert.getEncoded());
                RequestHelper.sendNewB64Cert(b64cert, res, RequestHelper.BEGIN_CERTIFICATE_WITH_NL,
                        RequestHelper.END_CERTIFICATE_WITH_NL);
            } else {
                RequestHelper.sendBinaryBytes(cert.getEncoded(), res, "application/octet-stream", "cert.crt");
            }
        } catch (Exception e) {
            String errMsg = intres.getLocalizedMessage("certreq.errorsendcert", remoteAddr, e.getMessage());
            log.error(errMsg, e);
            res.sendError(HttpServletResponse.SC_NOT_FOUND, errMsg);
            return;
        }
    }
    if (command.equalsIgnoreCase(COMMAND_CERTPKCS7)) {
        try {
            Certificate cert = cabean.getProcessedCertificate();
            byte[] pkcs7 = signSession.createPKCS7(ejbcawebbean.getAdminObject(), cert, true);
            byte[] b64cert = Base64.encode(pkcs7);
            RequestHelper.sendNewB64Cert(b64cert, res, RequestHelper.BEGIN_PKCS7_WITH_NL,
                    RequestHelper.END_PKCS7_WITH_NL);
        } catch (Exception e) {
            String errMsg = intres.getLocalizedMessage("certreq.errorsendcert", remoteAddr, e.getMessage());
            log.error(errMsg, e);
            res.sendError(HttpServletResponse.SC_NOT_FOUND, errMsg);
            return;
        }
    }
    if (command.equalsIgnoreCase(COMMAND_CERTLINK)) {
        try {
            final int caId = Integer.parseInt(req.getParameter(COMMAND_PROPERTY_CAID));
            final byte[] rawCert = cabean.getLinkCertificate(caId);
            if (rawCert != null) {
                if (!"binary".equals(format)) {
                    final byte[] b64cert = Base64.encode(rawCert);
                    RequestHelper.sendNewB64Cert(b64cert, res, RequestHelper.BEGIN_CERTIFICATE_WITH_NL,
                            RequestHelper.END_CERTIFICATE_WITH_NL);
                } else {
                    RequestHelper.sendBinaryBytes(rawCert, res, "application/octet-stream", "cert.crt");
                }
            }
        } catch (Exception e) {
            String errMsg = intres.getLocalizedMessage("certreq.errorsendcert", remoteAddr, e.getMessage());
            log.error(errMsg, e);
            res.sendError(HttpServletResponse.SC_NOT_FOUND, errMsg);
            return;
        }
    }
}

From source file:org.cesecore.util.CertTools.java

/**
 * Returns a certificate in PEM-format.//from  ww w .j  a v a 2  s . c  om
 * 
 * @param certs Collection of Certificate to convert to PEM
 * @return byte array containing PEM certificate
 * @throws CertificateEncodingException if an encoding error occurred
 */
public static byte[] getPemFromCertificateChain(Collection<Certificate> certs)
        throws CertificateEncodingException {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final PrintStream printStream = new PrintStream(baos);
    for (final Certificate certificate : certs) {
        printStream.println("Subject: " + CertTools.getSubjectDN(certificate));
        printStream.println("Issuer: " + CertTools.getIssuerDN(certificate));
        writeAsPemEncoded(printStream, certificate.getEncoded(), BEGIN_CERTIFICATE, END_CERTIFICATE);
    }
    printStream.close();
    return baos.toByteArray();
}

From source file:org.cesecore.util.CertTools.java

/**
 * Gets subject or issuer DN in the format we are sure about (BouncyCastle),supporting UTF8.
 * /*from w w  w .j  a v  a2  s . c  om*/
 * @param cert X509Certificate
 * @param which 1 = subjectDN, anything else = issuerDN
 * 
 * @return String containing the DN.
 */
private static String getDN(final Certificate cert, final int which) {
    String ret = null;
    if (cert == null) {
        return null;
    }
    if (cert instanceof X509Certificate) {
        // cert.getType=X.509
        try {
            final CertificateFactory cf = CertTools.getCertificateFactory();
            final X509Certificate x509cert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(cert.getEncoded()));
            String dn = null;
            if (which == 1) {
                dn = x509cert.getSubjectDN().toString();
            } else {
                dn = x509cert.getIssuerDN().toString();
            }
            ret = stringToBCDNString(dn);
        } catch (CertificateException ce) {
            log.info("Could not get DN from X509Certificate. " + ce.getMessage());
            log.debug("", ce);
            return null;
        }
    } else if (StringUtils.equals(cert.getType(), "CVC")) {
        final CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert;
        try {
            ReferenceField rf = null;
            if (which == 1) {
                rf = cvccert.getCVCertificate().getCertificateBody().getHolderReference();
            } else {
                rf = cvccert.getCVCertificate().getCertificateBody().getAuthorityReference();
            }
            if (rf != null) {
                // Construct a "fake" DN which can be used in EJBCA
                // Use only mnemonic and country, since sequence is more of a serialnumber than a DN part
                String dn = "";
                if (rf.getMnemonic() != null) {
                    if (StringUtils.isNotEmpty(dn)) {
                        dn += ", ";
                    }
                    dn += "CN=" + rf.getMnemonic();
                }
                if (rf.getCountry() != null) {
                    if (StringUtils.isNotEmpty(dn)) {
                        dn += ", ";
                    }
                    dn += "C=" + rf.getCountry();
                }
                ret = stringToBCDNString(dn);
            }
        } catch (NoSuchFieldException e) {
            log.error("NoSuchFieldException: ", e);
            return null;
        }
    }
    return ret;
}

From source file:com.cloud.network.resource.NitroError.java

private synchronized Answer execute(LoadBalancerConfigCommand cmd, int numRetries) {
    try {/*w  w w.j a  va  2 s  . c  o  m*/
        if (_isSdx) {
            return Answer.createUnsupportedCommandAnswer(cmd);
        }

        LoadBalancerTO[] loadBalancers = cmd.getLoadBalancers();
        if (loadBalancers == null) {
            return new Answer(cmd);
        }

        for (LoadBalancerTO loadBalancer : loadBalancers) {
            String srcIp = loadBalancer.getSrcIp();
            int srcPort = loadBalancer.getSrcPort();
            String lbProtocol = getNetScalerProtocol(loadBalancer);
            String lbAlgorithm = loadBalancer.getAlgorithm();
            String nsVirtualServerName = generateNSVirtualServerName(srcIp, srcPort);
            String nsMonitorName = generateNSMonitorName(srcIp, srcPort);
            LbSslCert sslCert = loadBalancer.getSslCert();

            if (loadBalancer.isAutoScaleVmGroupTO()) {
                applyAutoScaleConfig(loadBalancer);
                // Continue to process all the rules.
                continue;
            }
            boolean hasMonitor = false;
            boolean deleteMonitor = false;
            boolean destinationsToAdd = false;
            boolean deleteCert = false;
            for (DestinationTO destination : loadBalancer.getDestinations()) {
                if (!destination.isRevoked()) {
                    destinationsToAdd = true;
                    break;
                }
            }

            if (!loadBalancer.isRevoked() && destinationsToAdd) {

                // create a load balancing virtual server
                addLBVirtualServer(nsVirtualServerName, srcIp, srcPort, lbAlgorithm, lbProtocol,
                        loadBalancer.getStickinessPolicies(), null);
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Created load balancing virtual server " + nsVirtualServerName
                            + " on the Netscaler device");
                }

                // create a new monitor
                HealthCheckPolicyTO[] healthCheckPolicies = loadBalancer.getHealthCheckPolicies();
                if ((healthCheckPolicies != null) && (healthCheckPolicies.length > 0)
                        && (healthCheckPolicies[0] != null)) {

                    for (HealthCheckPolicyTO healthCheckPolicyTO : healthCheckPolicies) {
                        if (!healthCheckPolicyTO.isRevoked()) {
                            addLBMonitor(nsMonitorName, lbProtocol, healthCheckPolicyTO);
                            hasMonitor = true;
                        } else {
                            deleteMonitor = true;
                            hasMonitor = false;
                        }
                    }

                }

                for (DestinationTO destination : loadBalancer.getDestinations()) {

                    String nsServerName = generateNSServerName(destination.getDestIp());
                    String nsServiceName = generateNSServiceName(destination.getDestIp(),
                            destination.getDestPort());
                    if (!destination.isRevoked()) {
                        // add a new destination to deployed load balancing rule

                        // add a new server
                        if (!nsServerExists(nsServerName)) {
                            com.citrix.netscaler.nitro.resource.config.basic.server nsServer = new com.citrix.netscaler.nitro.resource.config.basic.server();
                            nsServer.set_name(nsServerName);
                            nsServer.set_ipaddress(destination.getDestIp());
                            apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.server
                                    .add(_netscalerService, nsServer);
                            if ((apiCallResult.errorcode != 0)
                                    && (apiCallResult.errorcode != NitroError.NS_RESOURCE_EXISTS)) {
                                throw new ExecutionException("Failed to add server " + destination.getDestIp()
                                        + " due to" + apiCallResult.message);
                            }
                        }

                        // create a new service using the server added
                        if (!nsServiceExists(nsServiceName)) {
                            com.citrix.netscaler.nitro.resource.config.basic.service newService = new com.citrix.netscaler.nitro.resource.config.basic.service();
                            newService.set_name(nsServiceName);
                            newService.set_port(destination.getDestPort());
                            newService.set_servername(nsServerName);
                            newService.set_state("ENABLED");
                            if (lbProtocol.equalsIgnoreCase(NetUtils.SSL_PROTO)) {
                                newService.set_servicetype(NetUtils.HTTP_PROTO);
                            } else {
                                newService.set_servicetype(lbProtocol);
                            }

                            apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.service
                                    .add(_netscalerService, newService);
                            if (apiCallResult.errorcode != 0) {
                                throw new ExecutionException("Failed to create service " + nsServiceName
                                        + " using server " + nsServerName + " due to" + apiCallResult.message);
                            }
                        }

                        //bind service to load balancing virtual server
                        if (!nsServiceBindingExists(nsVirtualServerName, nsServiceName)) {
                            com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding svcBinding = new com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding();
                            svcBinding.set_name(nsVirtualServerName);
                            svcBinding.set_servicename(nsServiceName);
                            apiCallResult = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding
                                    .add(_netscalerService, svcBinding);

                            if (apiCallResult.errorcode != 0) {
                                throw new ExecutionException("Failed to bind service: " + nsServiceName
                                        + " to the lb virtual server: " + nsVirtualServerName
                                        + " on Netscaler device");
                            }
                        }

                        // After binding the service to the LB Vserver
                        // successfully, bind the created monitor to the
                        // service.
                        if (hasMonitor) {
                            if (!isServiceBoundToMonitor(nsServiceName, nsMonitorName)) {
                                bindServiceToMonitor(nsServiceName, nsMonitorName);
                            }
                        } else {
                            // check if any monitor created by CS is already
                            // existing, if yes, unbind it from services and
                            // delete it.
                            if (nsMonitorExist(nsMonitorName)) {
                                // unbind the service from the monitor and
                                // delete the monitor
                                unBindServiceToMonitor(nsServiceName, nsMonitorName);
                                deleteMonitor = true;
                            }

                        }

                        if (sslCert != null && lbProtocol.equalsIgnoreCase(NetUtils.SSL_PROTO)) {
                            if (sslCert.isRevoked()) {
                                deleteCert = true;
                            } else {

                                // If there is a chain, that should go first to the NS

                                String previousCertKeyName = null;

                                if (sslCert.getChain() != null) {
                                    List<Certificate> chainList = CertificateHelper
                                            .parseChain(sslCert.getChain());
                                    // go from ROOT to intermediate CAs
                                    for (Certificate intermediateCert : Lists.reverse(chainList)) {

                                        String fingerPrint = CertificateHelper
                                                .generateFingerPrint(intermediateCert);
                                        String intermediateCertKeyName = generateSslCertKeyName(fingerPrint);
                                        String intermediateCertFileName = intermediateCertKeyName + ".pem";

                                        if (!SSL.isSslCertKeyPresent(_netscalerService,
                                                intermediateCertKeyName)) {
                                            intermediateCert.getEncoded();
                                            StringWriter textWriter = new StringWriter();
                                            PEMWriter pemWriter = new PEMWriter(textWriter);
                                            pemWriter.writeObject(intermediateCert);
                                            pemWriter.flush();

                                            SSL.uploadCert(_ip, _username, _password, intermediateCertFileName,
                                                    textWriter.toString().getBytes());
                                            SSL.createSslCertKey(_netscalerService, intermediateCertFileName,
                                                    null, intermediateCertKeyName, null);
                                        }

                                        if (previousCertKeyName != null
                                                && !SSL.certLinkExists(_netscalerService,
                                                        intermediateCertKeyName, previousCertKeyName)) {
                                            SSL.linkCerts(_netscalerService, intermediateCertKeyName,
                                                    previousCertKeyName);
                                        }

                                        previousCertKeyName = intermediateCertKeyName;
                                    }
                                }

                                String certFilename = generateSslCertName(sslCert.getFingerprint()) + ".pem"; //netscaler uses ".pem" format for "bundle" files
                                String keyFilename = generateSslKeyName(sslCert.getFingerprint()) + ".pem"; //netscaler uses ".pem" format for "bundle" files
                                String certKeyName = generateSslCertKeyName(sslCert.getFingerprint());

                                ByteArrayOutputStream certDataStream = new ByteArrayOutputStream();
                                certDataStream.write(sslCert.getCert().getBytes());

                                if (!SSL.isSslCertKeyPresent(_netscalerService, certKeyName)) {

                                    SSL.uploadCert(_ip, _username, _password, certFilename,
                                            certDataStream.toByteArray());
                                    SSL.uploadKey(_ip, _username, _password, keyFilename,
                                            sslCert.getKey().getBytes());
                                    SSL.createSslCertKey(_netscalerService, certFilename, keyFilename,
                                            certKeyName, sslCert.getPassword());
                                }

                                if (previousCertKeyName != null && !SSL.certLinkExists(_netscalerService,
                                        certKeyName, previousCertKeyName)) {
                                    SSL.linkCerts(_netscalerService, certKeyName, previousCertKeyName);
                                }

                                SSL.bindCertKeyToVserver(_netscalerService, certKeyName, nsVirtualServerName);
                            }

                        }

                        if (s_logger.isDebugEnabled()) {
                            s_logger.debug("Successfully added LB destination: " + destination.getDestIp() + ":"
                                    + destination.getDestPort() + " to load balancer " + srcIp + ":" + srcPort);
                        }

                    } else {
                        // remove a destination from the deployed load balancing rule
                        com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding[] serviceBindings = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding
                                .get(_netscalerService, nsVirtualServerName);
                        if (serviceBindings != null) {
                            for (com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding binding : serviceBindings) {
                                if (nsServiceName.equalsIgnoreCase(binding.get_servicename())) {
                                    // delete the binding
                                    apiCallResult = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding
                                            .delete(_netscalerService, binding);
                                    if (apiCallResult.errorcode != 0) {
                                        throw new ExecutionException(
                                                "Failed to delete the binding between the virtual server: "
                                                        + nsVirtualServerName + " and service:" + nsServiceName
                                                        + " due to" + apiCallResult.message);
                                    }

                                    // check if service is bound to any other virtual server
                                    if (!isServiceBoundToVirtualServer(nsServiceName)) {
                                        // no lb virtual servers are bound to this service so delete it
                                        apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.service
                                                .delete(_netscalerService, nsServiceName);
                                        if (apiCallResult.errorcode != 0) {
                                            throw new ExecutionException("Failed to delete service: "
                                                    + nsServiceName + " due to " + apiCallResult.message);
                                        }
                                    }

                                    // delete the server if there is no associated services
                                    server_service_binding[] services = server_service_binding
                                            .get(_netscalerService, nsServerName);
                                    if ((services == null) || (services.length == 0)) {
                                        apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.server
                                                .delete(_netscalerService, nsServerName);
                                        if (apiCallResult.errorcode != 0) {
                                            throw new ExecutionException("Failed to remove server:"
                                                    + nsServerName + " due to " + apiCallResult.message);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                // delete the implemented load balancing rule and its destinations
                lbvserver lbserver = getVirtualServerIfExisits(nsVirtualServerName);
                if (lbserver != null) {
                    //unbind the all services associated with this virtual server
                    com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding[] serviceBindings = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding
                            .get(_netscalerService, nsVirtualServerName);

                    if (serviceBindings != null) {
                        for (com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding binding : serviceBindings) {
                            String serviceName = binding.get_servicename();
                            apiCallResult = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding
                                    .delete(_netscalerService, binding);
                            if (apiCallResult.errorcode != 0) {
                                throw new ExecutionException(
                                        "Failed to unbind service from the lb virtual server: "
                                                + nsVirtualServerName + " due to " + apiCallResult.message);
                            }

                            com.citrix.netscaler.nitro.resource.config.basic.service svc = com.citrix.netscaler.nitro.resource.config.basic.service
                                    .get(_netscalerService, serviceName);
                            String nsServerName = svc.get_servername();

                            // check if service is bound to any other virtual server
                            if (!isServiceBoundToVirtualServer(serviceName)) {
                                // no lb virtual servers are bound to this service so delete it
                                apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.service
                                        .delete(_netscalerService, serviceName);
                                if (apiCallResult.errorcode != 0) {
                                    throw new ExecutionException("Failed to delete service: " + serviceName
                                            + " due to " + apiCallResult.message);
                                }
                            }

                            //delete the server if no more services attached
                            server_service_binding[] services = server_service_binding.get(_netscalerService,
                                    nsServerName);
                            if ((services == null) || (services.length == 0)) {
                                apiCallResult = com.citrix.netscaler.nitro.resource.config.basic.server
                                        .delete(_netscalerService, nsServerName);
                                if (apiCallResult.errorcode != 0) {
                                    throw new ExecutionException("Failed to remove server:" + nsServerName
                                            + " due to " + apiCallResult.message);
                                }
                            }
                        }
                    }
                    removeLBVirtualServer(nsVirtualServerName);
                    deleteMonitor = true;
                    deleteCert = true;
                }
            }
            if (deleteMonitor) {
                removeLBMonitor(nsMonitorName);
            }
            if (sslCert != null && deleteCert) {

                String certFilename = generateSslCertName(sslCert.getFingerprint()) + ".pem"; //netscaler uses ".pem" format for "bundle" files
                String keyFilename = generateSslKeyName(sslCert.getFingerprint()) + ".pem"; //netscaler uses ".pem" format for "bundle" files
                String certKeyName = generateSslCertKeyName(sslCert.getFingerprint());

                // unbind before deleting
                if (nsVirtualServerExists(nsVirtualServerName)
                        && SSL.isSslCertKeyPresent(_netscalerService, certKeyName)
                        && SSL.isBoundToVserver(_netscalerService, certKeyName, nsVirtualServerName)) {
                    SSL.unbindCertKeyFromVserver(_netscalerService, certKeyName, nsVirtualServerName);
                }

                if (SSL.isSslCertKeyPresent(_netscalerService, certKeyName)) {

                    SSL.deleteSslCertKey(_netscalerService, certKeyName);
                    SSL.deleteCertFile(_ip, _username, _password, certFilename);
                    SSL.deleteKeyFile(_ip, _username, _password, keyFilename);
                }

                /*
                 * Check and delete intermediate certs:
                 * we can delete an intermediate cert if no other
                 * cert references it as the athority
                 */

                if (sslCert.getChain() != null) {
                    List<Certificate> chainList = CertificateHelper.parseChain(sslCert.getChain());
                    //go from intermediate CAs to ROOT
                    for (Certificate intermediateCert : chainList) {

                        String fingerPrint = CertificateHelper.generateFingerPrint(intermediateCert);
                        String intermediateCertKeyName = generateSslCertKeyName(fingerPrint);
                        String intermediateCertFileName = intermediateCertKeyName + ".pem";

                        if (SSL.isSslCertKeyPresent(_netscalerService, intermediateCertKeyName)
                                && !SSL.isCaforCerts(_netscalerService, intermediateCertKeyName)) {
                            SSL.deleteSslCertKey(_netscalerService, intermediateCertKeyName);
                            SSL.deleteCertFile(_ip, _username, _password, intermediateCertFileName);
                        } else {
                            break;// if this cert has another certificate as a child then stop at this point because we need the whole chain
                        }

                    }
                }
            }

        }

        if (s_logger.isInfoEnabled()) {
            s_logger.info("Successfully executed resource LoadBalancerConfigCommand: " + _gson.toJson(cmd));
        }

        saveConfiguration();
        return new Answer(cmd);
    } catch (ExecutionException e) {
        s_logger.error("Failed to execute LoadBalancerConfigCommand due to ", e);
        if (shouldRetry(numRetries)) {
            return retry(cmd, numRetries);
        } else {
            return new Answer(cmd, e);
        }
    } catch (Exception e) {
        s_logger.error("Failed to execute LoadBalancerConfigCommand due to ", e);
        if (shouldRetry(numRetries)) {
            return retry(cmd, numRetries);
        } else {
            return new Answer(cmd, e);
        }
    }
}

From source file:org.ejbca.core.model.ca.publisher.LdapPublisher.java

/**
 * Publishes certificate in LDAP, if the certificate is not revoked. If the certificate is revoked, nothing is done
 * and the publishing is counted as successful (i.e. returns true).
 * //w ww. j  a v  a2s .co  m
 * @see org.ejbca.core.model.ca.publisher.BasePublisher#storeCertificate
 */
public boolean storeCertificate(AuthenticationToken admin, Certificate incert, String username, String password,
        String userDN, String cafp, int status, int type, long revocationDate, int revocationReason, String tag,
        int certificateProfileId, long lastUpdate, ExtendedInformation extendedinformation)
        throws PublisherException {
    if (log.isTraceEnabled()) {
        log.trace(">storeCertificate(username=" + username + ")");
    }

    if (status == CertificateConstants.CERT_REVOKED) {
        // Call separate script for revocation
        revokeCertificate(admin, incert, username, revocationReason, userDN);
    } else if (status == CertificateConstants.CERT_ACTIVE) {
        // Don't publish non-active certificates
        int ldapVersion = LDAPConnection.LDAP_V3;
        LDAPConnection lc = createLdapConnection();

        final String dn;
        final String certdn;
        try {
            // Extract the users DN from the cert.
            certdn = CertTools.getSubjectDN(incert);
            if (log.isDebugEnabled()) {
                log.debug("Constructing DN for: " + username);
            }
            dn = constructLDAPDN(certdn, userDN);
            if (log.isDebugEnabled()) {
                log.debug("LDAP DN for user " + username + " is '" + dn + "'");
            }
        } catch (Exception e) {
            String msg = intres.getLocalizedMessage("publisher.errorldapdecode", "certificate");
            log.error(msg, e);
            throw new PublisherException(msg);
        }

        // Extract the users email from the cert.
        String email = CertTools.getEMailAddress(incert);

        // Check if the entry is already present, we will update it with the new certificate.
        // To work well with the LdapSearchPublisher we need to pass the full certificate DN to the 
        // search function, and not only the LDAP DN. The regular publisher should only use the LDAP DN though, 
        // but the searchOldEntity function will take care of that.
        LDAPEntry oldEntry = searchOldEntity(username, ldapVersion, lc, certdn, userDN, email);

        // PART 2: Create LDAP entry
        LDAPEntry newEntry = null;
        ArrayList<LDAPModification> modSet = new ArrayList<LDAPModification>();
        LDAPAttributeSet attributeSet = null;
        String attribute = null;
        String objectclass = null;

        if (type == CertificateConstants.CERTTYPE_ENDENTITY) {
            if (log.isDebugEnabled()) {
                log.debug("Publishing end user certificate to first available server of " + getHostnames());
            }
            if (oldEntry != null) {
                modSet = getModificationSet(oldEntry, certdn, email, ADD_MODIFICATION_ATTRIBUTES, true,
                        password, incert);
            } else {
                objectclass = getUserObjectClass(); // just used for logging
                attributeSet = getAttributeSet(incert, getUserObjectClass(), certdn, email, true, true,
                        password, extendedinformation);
            }

            try {
                attribute = getUserCertAttribute();
                LDAPAttribute certAttr = new LDAPAttribute(getUserCertAttribute(), incert.getEncoded());
                if (oldEntry != null) {
                    String oldDn = oldEntry.getDN();
                    if (getAddMultipleCertificates()) {
                        modSet.add(new LDAPModification(LDAPModification.ADD, certAttr));
                        if (log.isDebugEnabled()) {
                            log.debug("Appended new certificate in user entry; " + username + ": " + oldDn);
                        }
                    } else {
                        modSet.add(new LDAPModification(LDAPModification.REPLACE, certAttr));
                        if (log.isDebugEnabled()) {
                            log.debug("Replaced certificate in user entry; " + username + ": " + oldDn);
                        }
                    }
                } else {
                    attributeSet.add(certAttr);
                    if (log.isDebugEnabled()) {
                        log.debug("Added new certificate to user entry; " + username + ": " + dn);
                    }
                }
            } catch (CertificateEncodingException e) {
                String msg = intres.getLocalizedMessage("publisher.errorldapencodestore", "certificate");
                log.error(msg, e);
                throw new PublisherException(msg);
            }
        } else if (type == CertificateConstants.CERTTYPE_SUBCA
                || type == CertificateConstants.CERTTYPE_ROOTCA) {
            if (log.isDebugEnabled()) {
                log.debug("Publishing CA certificate to first available server of " + getHostnames());
            }
            if (oldEntry != null) {
                modSet = getModificationSet(oldEntry, certdn, null, false, false, password, incert);
            } else {
                objectclass = getCAObjectClass(); // just used for logging
                attributeSet = getAttributeSet(incert, getCAObjectClass(), certdn, null, true, false, password,
                        extendedinformation);
            }
            try {
                attribute = getCACertAttribute();
                LDAPAttribute certAttr = new LDAPAttribute(getCACertAttribute(), incert.getEncoded());
                if (oldEntry != null) {
                    modSet.add(new LDAPModification(LDAPModification.REPLACE, certAttr));
                } else {
                    attributeSet.add(certAttr);
                    // Also create using the crlattribute, it may be required
                    LDAPAttribute crlAttr = new LDAPAttribute(getCRLAttribute(), getFakeCRL());
                    attributeSet.add(crlAttr);
                    // Also create using the arlattribute, it may be required
                    LDAPAttribute arlAttr = new LDAPAttribute(getARLAttribute(), getFakeCRL());
                    attributeSet.add(arlAttr);
                    if (log.isDebugEnabled()) {
                        log.debug("Added (fake) attribute for CRL and ARL.");
                    }
                }
            } catch (CertificateEncodingException e) {
                String msg = intres.getLocalizedMessage("publisher.errorldapencodestore", "certificate");
                log.error(msg, e);
                throw new PublisherException(msg);
            }
        } else {
            String msg = intres.getLocalizedMessage("publisher.notpubltype", Integer.valueOf(type));
            log.info(msg);
            throw new PublisherException(msg);
        }

        // PART 3: MODIFICATION AND ADDITION OF NEW USERS
        // Try all the listed servers
        Iterator<String> servers = getHostnameList().iterator();
        boolean connectionFailed;
        do {
            connectionFailed = false;
            String currentServer = servers.next();
            try {
                TCPTool.probeConnectionLDAP(currentServer, Integer.parseInt(getPort()), getConnectionTimeOut()); // Avoid waiting for halfdead-servers
                lc.connect(currentServer, Integer.parseInt(getPort()));
                // Execute a STARTTLS handshake if it was requested.
                if (getConnectionSecurity() == ConnectionSecurity.STARTTLS) {
                    if (log.isDebugEnabled()) {
                        log.debug("STARTTLS to LDAP server " + currentServer);
                    }
                    lc.startTLS();
                }
                // authenticate to the server
                lc.bind(ldapVersion, getLoginDN(), getLoginPassword().getBytes("UTF8"), ldapBindConstraints);
                // Add or modify the entry
                if (oldEntry != null && getModifyExistingUsers()) {
                    LDAPModification[] mods = new LDAPModification[modSet.size()];
                    mods = (LDAPModification[]) modSet.toArray(mods);
                    String oldDn = oldEntry.getDN();
                    if (log.isDebugEnabled()) {
                        log.debug("Writing modification to DN: " + oldDn);
                    }
                    lc.modify(oldDn, mods, ldapStoreConstraints);
                    String msg = intres.getLocalizedMessage("publisher.ldapmodify", "CERT", oldDn);
                    log.info(msg);
                } else {
                    if (this.getCreateNonExistingUsers()) {
                        if (oldEntry == null) {
                            // Check if the intermediate parent node is present, and if it is not
                            // we can create it, of allowed to do so by the publisher configuration
                            if (getCreateIntermediateNodes()) {
                                final String parentDN = CertTools.getParentDN(dn);
                                try {
                                    lc.read(parentDN, ldapSearchConstraints);
                                } catch (LDAPException e) {
                                    if (e.getResultCode() == LDAPException.NO_SUCH_OBJECT) {
                                        this.createIntermediateNodes(lc, dn);
                                        String msg = intres.getLocalizedMessage(
                                                "publisher.ldapaddedintermediate", "CERT", parentDN);
                                        log.info(msg);
                                    }
                                }
                            }
                            newEntry = new LDAPEntry(dn, attributeSet);
                            if (log.isDebugEnabled()) {
                                log.debug("Adding DN: " + dn);
                            }
                            lc.add(newEntry, ldapStoreConstraints);
                            String msg = intres.getLocalizedMessage("publisher.ldapadd", "CERT", dn);
                            log.info(msg);
                        }
                    }
                }
            } catch (LDAPException e) {
                connectionFailed = true;
                // If multiple certificates are allowed per entity, and the certificate is already published, 
                // an exception will be thrown. Catch this type of exception and just log an informational message.
                if (e.getResultCode() == LDAPException.ATTRIBUTE_OR_VALUE_EXISTS) {
                    final String msg = intres.getLocalizedMessage("publisher.certalreadyexists",
                            CertTools.getFingerprintAsString(incert), dn, e.getMessage());
                    log.info(msg);
                } else if (servers.hasNext()) {
                    log.warn("Failed to publish to " + currentServer + ". Trying next in list.");
                } else {
                    String msg = intres.getLocalizedMessage("publisher.errorldapstore", "certificate",
                            attribute, objectclass, dn, e.getMessage());
                    log.error(msg, e);
                    throw new PublisherException(msg);
                }
            } catch (UnsupportedEncodingException e) {
                String msg = intres.getLocalizedMessage("publisher.errorpassword", getLoginPassword());
                log.error(msg, e);
                throw new PublisherException(msg);
            } finally {
                // disconnect with the server
                try {
                    lc.disconnect(ldapDisconnectConstraints);
                } catch (LDAPException e) {
                    String msg = intres.getLocalizedMessage("publisher.errordisconnect", getLoginPassword());
                    log.error(msg, e);
                }
            }
        } while (connectionFailed && servers.hasNext());
    } else {
        String msg = intres.getLocalizedMessage("publisher.notpublwithstatus", Integer.valueOf(status));
        log.info(msg);
    }
    if (log.isTraceEnabled()) {
        log.trace("<storeCertificate()");
    }
    return true;
}

From source file:org.cesecore.certificates.certificate.CertificateCreateSessionBean.java

@Override
public CertificateDataWrapper createCertificate(final AuthenticationToken admin,
        final EndEntityInformation endEntityInformation, final CA ca, final RequestMessage request,
        final PublicKey pk, final int keyusage, final Date notBefore, final Date notAfter,
        final Extensions extensions, final String sequence, CertificateGenerationParams certGenParams,
        final long updateTime) throws AuthorizationDeniedException, IllegalNameException,
        CustomCertificateSerialNumberException, CertificateCreateException, CertificateRevokeException,
        CertificateSerialNumberException, CryptoTokenOfflineException, IllegalKeyException,
        CertificateExtensionException, IllegalValidityException, CAOfflineException, InvalidAlgorithmException {
    if (log.isTraceEnabled()) {
        log.trace(//from  ww  w  .j  a v a 2  s  . c  o m
                ">createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)");
    }

    // Even though CA is passed as an argument to this method, we do check authorization on that.
    // To make sure we properly log authorization checks needed to issue a cert.
    // We need to check that admin have rights to create certificates, and have access to the CA
    if (!accessSession.isAuthorized(admin, StandardRules.CREATECERT.resource(),
            StandardRules.CAACCESS.resource() + ca.getCAId())) {
        final String msg = intres.getLocalizedMessage("createcert.notauthorized", admin.toString(),
                ca.getCAId());
        throw new AuthorizationDeniedException(msg);
    }

    // Audit log that we received the request
    final Map<String, Object> details = new LinkedHashMap<String, Object>();
    details.put("subjectdn", endEntityInformation.getDN());
    details.put("requestX500name", (request == null || request.getRequestX500Name() == null) ? "null"
            : request.getRequestX500Name().toString());
    details.put("certprofile", endEntityInformation.getCertificateProfileId());
    details.put("keyusage", keyusage);
    details.put("notbefore", notBefore);
    details.put("notafter", notAfter);
    details.put("sequence", sequence);
    details.put("publickey", new String(Base64.encode(pk.getEncoded(), false)));
    logSession.log(EventTypes.CERT_REQUEST, EventStatus.SUCCESS, ModuleTypes.CERTIFICATE, ServiceTypes.CORE,
            admin.toString(), String.valueOf(ca.getCAId()), null, endEntityInformation.getUsername(), details);

    // Set up audit logging of CT pre-certificate
    addCTLoggingCallback(certGenParams, admin.toString());

    try {
        CertificateDataWrapper result = null;
        // If the user is of type USER_INVALID, it cannot have any other type (in the mask)
        if (endEntityInformation.getType().isType(EndEntityTypes.INVALID)) {
            final String msg = intres.getLocalizedMessage("createcert.usertypeinvalid",
                    endEntityInformation.getUsername());
            throw new CertificateCreateException(msg);
        }
        final Certificate cacert = ca.getCACertificate();
        final String caSubjectDN = CertTools.getSubjectDN(cacert);
        assertSubjectEnforcements(ca, caSubjectDN, endEntityInformation, pk);
        // Retrieve the certificate profile this user should have, checking for authorization to the profile
        final int certProfileId = endEntityInformation.getCertificateProfileId();
        final CertificateProfile certProfile = getCertificateProfile(certProfileId, ca.getCAId());

        // Check that the request public key fulfills policy
        verifyKey(pk, certProfile);

        // Below we have a small loop if it would happen that we generate the same serial number twice
        // If using only 4 byte serial numbers this do happen once in a while
        Certificate cert = null;
        String cafingerprint = null;
        String serialNo = "unknown";
        final boolean useCustomSN;
        {
            final ExtendedInformation ei = endEntityInformation.getExtendedinformation();
            useCustomSN = ei != null && ei.certificateSerialNumber() != null;
        }
        final int maxRetrys;
        if (useCustomSN) {
            if (ca.isUseCertificateStorage() && !isUniqueCertificateSerialNumberIndex()) {
                final String msg = intres.getLocalizedMessage("createcert.not_unique_certserialnumberindex");
                log.error(msg);
                throw new CustomCertificateSerialNumberException(msg);
            }
            if (!certProfile.getAllowCertSerialNumberOverride()) {
                final String msg = intres.getLocalizedMessage(
                        "createcert.certprof_not_allowing_cert_sn_override", Integer.valueOf(certProfileId));
                log.info(msg);
                throw new CustomCertificateSerialNumberException(msg);
            }
            maxRetrys = 1;
        } else {
            maxRetrys = 5;
        }

        // Before storing the new certificate, check if single active certificate constraint is active, and if so let's revoke all active and unexpired certificates
        if (certProfile.isSingleActiveCertificateConstraint()) {
            for (Certificate certificate : certificateStoreSession.findCertificatesBySubjectAndIssuer(
                    endEntityInformation.getCertificateDN(), caSubjectDN, true)) {
                //Authorization to the CA was already checked at the head of this method, so no need to do so now
                certificateStoreSession.setRevokeStatusNoAuth(admin, certificate, new Date(),
                        RevokedCertInfo.REVOCATION_REASON_SUPERSEDED, endEntityInformation.getDN());
            }
        }

        CertificateSerialNumberException storeEx = null; // this will not be null if stored == false after the below passage
        for (int retrycounter = 0; retrycounter < maxRetrys; retrycounter++) {
            final CryptoToken cryptoToken = cryptoTokenManagementSession
                    .getCryptoToken(ca.getCAToken().getCryptoTokenId());
            if (cryptoToken == null) {
                final String msg = intres.getLocalizedMessage("error.catokenoffline", ca.getCAId());
                log.info(msg);
                CryptoTokenOfflineException exception = new CryptoTokenOfflineException(
                        "CA's CryptoToken not found.");
                auditFailure(admin, exception, exception.getMessage(),
                        "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)",
                        ca.getCAId(), endEntityInformation.getUsername());
                throw exception;
            }
            cert = ca.generateCertificate(cryptoToken, endEntityInformation, request, pk, keyusage, notBefore,
                    notAfter, certProfile, extensions, sequence, certGenParams);
            serialNo = CertTools.getSerialNumberAsString(cert);
            cafingerprint = CertTools.getFingerprintAsString(cacert);
            // Store certificate in the database, if this CA is configured to do so.
            if (!ca.isUseCertificateStorage()) {
                result = new CertificateDataWrapper(cert, null, null);
                break; // We have our cert and we don't need to store it.. Move on..
            }
            try {
                // Remember for CVC serialNo can be alphanumeric, so we can't just try to decode that using normal Java means (BigInteger.valueOf)...
                assertSerialNumberForIssuerOk(ca, caSubjectDN, CertTools.getSerialNumber(cert));
                // Tag is reserved for future use, currently only null
                final String tag = null;
                // Authorization was already checked by since this is a private method, the CA parameter should
                // not be possible to get without authorization
                result = certificateStoreSession.storeCertificateNoAuth(admin, cert,
                        endEntityInformation.getUsername(), cafingerprint, CertificateConstants.CERT_ACTIVE,
                        certProfile.getType(), certProfileId, tag, updateTime);
                storeEx = null;
                break;
            } catch (CertificateSerialNumberException e) {
                // If we have created a unique index on (issuerDN,serialNumber) on table CertificateData we can
                // get a CreateException here if we would happen to generate a certificate with the same serialNumber
                // as one already existing certificate.
                if (retrycounter + 1 < maxRetrys) {
                    log.info("Can not store certificate with serNo (" + serialNo
                            + "), will retry (retrycounter=" + retrycounter
                            + ") with a new certificate with new serialNo: " + e.getMessage());
                }
                storeEx = e;
            }
        }
        if (storeEx != null) {
            if (useCustomSN) {
                final String msg = intres
                        .getLocalizedMessage("createcert.cert_serial_number_already_in_database", serialNo);
                log.info(msg);
                throw new CustomCertificateSerialNumberException(msg);
            }
            log.error("Can not store certificate in database in 5 tries, aborting: ", storeEx);
            throw storeEx;
        }

        // Finally we check if this certificate should not be issued as active, but revoked directly upon issuance
        int revreason = RevokedCertInfo.NOT_REVOKED;
        ExtendedInformation ei = endEntityInformation.getExtendedinformation();
        if (ei != null) {
            revreason = ei.getIssuanceRevocationReason();
            if (revreason != RevokedCertInfo.NOT_REVOKED) {
                // If we don't store the certificate in the database, we wont support revocation/reactivation so issuing revoked certificates would be
                // really strange.
                if (ca.isUseCertificateStorage()) {
                    certificateStoreSession.setRevokeStatusNoAuth(admin, cert, new Date(), revreason,
                            endEntityInformation.getDN());
                } else {
                    log.warn(
                            "CA configured to revoke issued certificates directly, but not to store issued the certificates. Revocation will be ignored. Please verify your configuration.");
                }
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Generated certificate with SerialNumber '" + serialNo + "' for user '"
                    + endEntityInformation.getUsername() + "', with revocation reason=" + revreason);
            log.debug(cert.toString());
        }

        // Audit log that we issued the certificate
        final Map<String, Object> issuedetails = new LinkedHashMap<String, Object>();
        issuedetails.put("subjectdn", endEntityInformation.getDN());
        issuedetails.put("certprofile", endEntityInformation.getCertificateProfileId());
        issuedetails.put("issuancerevocationreason", revreason);
        try {
            issuedetails.put("cert", new String(Base64.encode(cert.getEncoded(), false)));
        } catch (CertificateEncodingException e) {
            //Should not be able to happen at this point
            throw new IllegalStateException();
        }
        logSession.log(EventTypes.CERT_CREATION, EventStatus.SUCCESS, ModuleTypes.CERTIFICATE,
                ServiceTypes.CORE, admin.toString(), String.valueOf(ca.getCAId()), serialNo,
                endEntityInformation.getUsername(), issuedetails);

        if (log.isTraceEnabled()) {
            log.trace(
                    "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)");
        }
        return result;
        // We need to catch and re-throw all of these exception just because we need to audit log all failures
    } catch (CustomCertificateSerialNumberException e) {
        log.info(e.getMessage());
        auditFailure(admin, e, null,
                "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)",
                ca.getCAId(), endEntityInformation.getUsername());
        throw e;
    } catch (AuthorizationDeniedException e) {
        log.info(e.getMessage());
        auditFailure(admin, e, null,
                "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)",
                ca.getCAId(), endEntityInformation.getUsername());
        throw e;
    } catch (CertificateCreateException e) {
        log.info(e.getMessage());
        auditFailure(admin, e, null,
                "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)",
                ca.getCAId(), endEntityInformation.getUsername());
        // Rollback
        throw e;
    } catch (CryptoTokenOfflineException e) {
        final String msg = intres.getLocalizedMessage("error.catokenoffline", ca.getCAId());
        log.info(msg);
        auditFailure(admin, e, e.getMessage(),
                "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)",
                ca.getCAId(), endEntityInformation.getUsername());
        throw e;
    } catch (CAOfflineException e) {
        log.error("Error creating certificate", e);
        auditFailure(admin, e, null,
                "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)",
                ca.getCAId(), endEntityInformation.getUsername());
        throw e;
    } catch (InvalidAlgorithmException e) {
        log.error("Error creating certificate", e);
        auditFailure(admin, e, null,
                "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)",
                ca.getCAId(), endEntityInformation.getUsername());
        throw e;
    } catch (IllegalValidityException e) {
        log.error("Error creating certificate", e);
        auditFailure(admin, e, null,
                "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)",
                ca.getCAId(), endEntityInformation.getUsername());
        throw e;
    } catch (OperatorCreationException e) {
        log.error("Error creating certificate", e);
        auditFailure(admin, e, null,
                "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)",
                ca.getCAId(), endEntityInformation.getUsername());
        // Rollback
        throw new CertificateCreateException(e);
    } catch (SignatureException e) {
        log.error("Error creating certificate", e);
        auditFailure(admin, e, null,
                "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)",
                ca.getCAId(), endEntityInformation.getUsername());
        // Rollback
        throw new CertificateCreateException(e);
    } catch (CertificateExtensionException e) {
        log.error("Error creating certificate", e);
        auditFailure(admin, e, null,
                "<createCertificate(EndEntityInformation, CA, X500Name, pk, ku, notBefore, notAfter, extesions, sequence)",
                ca.getCAId(), endEntityInformation.getUsername());
        throw e;
    }

}

From source file:com.codename1.impl.android.AndroidImplementation.java

@Override
public String[] getSSLCertificates(Object connection, String url) throws IOException {
    if (connection instanceof HttpsURLConnection) {
        HttpsURLConnection conn = (HttpsURLConnection) connection;

        try {/*  w  w  w . j  a v  a2 s .  c o  m*/
            conn.connect();
            java.security.cert.Certificate[] certs = conn.getServerCertificates();
            String[] out = new String[certs.length];
            int i = 0;
            for (java.security.cert.Certificate cert : certs) {
                MessageDigest md = MessageDigest.getInstance("SHA1");
                md.update(cert.getEncoded());
                out[i++] = "SHA1:" + dumpHex(md.digest());
            }
            return out;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return new String[0];

}