Example usage for java.security.cert X509Certificate getIssuerDN

List of usage examples for java.security.cert X509Certificate getIssuerDN

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getIssuerDN.

Prototype

public abstract Principal getIssuerDN();

Source Link

Document

Denigrated, replaced by #getIssuerX500Principal() .

Usage

From source file:android.net.http.CertificateChainValidator.java

/**
 * Performs the handshake and server certificates validation
 * @param sslSocket The secure connection socket
 * @param domain The website domain// ww  w .ja va2 s .com
 * @return An SSL error object if there is an error and null otherwise
 */
public SslError doHandshakeAndValidateServerCertificates(HttpsConnection connection, SSLSocket sslSocket,
        String domain) throws SSLHandshakeException, IOException {

    ++sTotal;

    SSLContext sslContext = HttpsConnection.getContext();
    if (sslContext == null) {
        closeSocketThrowException(sslSocket, "SSL context is null");
    }

    X509Certificate[] serverCertificates = null;

    long sessionBeforeHandshakeLastAccessedTime = 0;
    byte[] sessionBeforeHandshakeId = null;

    SSLSession sessionAfterHandshake = null;

    synchronized (sslContext) {
        // get SSL session before the handshake
        SSLSession sessionBeforeHandshake = getSSLSession(sslContext, connection.getHost());
        if (sessionBeforeHandshake != null) {
            sessionBeforeHandshakeLastAccessedTime = sessionBeforeHandshake.getLastAccessedTime();

            sessionBeforeHandshakeId = sessionBeforeHandshake.getId();
        }

        // start handshake, close the socket if we fail
        try {
            sslSocket.setUseClientMode(true);
            sslSocket.startHandshake();
        } catch (IOException e) {
            closeSocketThrowException(sslSocket, e.getMessage(), "failed to perform SSL handshake");
        }

        // retrieve the chain of the server peer certificates
        Certificate[] peerCertificates = sslSocket.getSession().getPeerCertificates();

        if (peerCertificates == null || peerCertificates.length <= 0) {
            closeSocketThrowException(sslSocket, "failed to retrieve peer certificates");
        } else {
            serverCertificates = new X509Certificate[peerCertificates.length];
            for (int i = 0; i < peerCertificates.length; ++i) {
                serverCertificates[i] = (X509Certificate) (peerCertificates[i]);
            }

            // update the SSL certificate associated with the connection
            if (connection != null) {
                if (serverCertificates[0] != null) {
                    connection.setCertificate(new SslCertificate(serverCertificates[0]));
                }
            }
        }

        // get SSL session after the handshake
        sessionAfterHandshake = getSSLSession(sslContext, connection.getHost());
    }

    if (sessionBeforeHandshakeLastAccessedTime != 0 && sessionAfterHandshake != null
            && Arrays.equals(sessionBeforeHandshakeId, sessionAfterHandshake.getId())
            && sessionBeforeHandshakeLastAccessedTime < sessionAfterHandshake.getLastAccessedTime()) {

        if (HttpLog.LOGV) {
            HttpLog.v("SSL session was reused: total reused: " + sTotalReused + " out of total of: " + sTotal);

            ++sTotalReused;
        }

        // no errors!!!
        return null;
    }

    // check if the first certificate in the chain is for this site
    X509Certificate currCertificate = serverCertificates[0];
    if (currCertificate == null) {
        closeSocketThrowException(sslSocket, "certificate for this site is null");
    } else {
        if (!DomainNameChecker.match(currCertificate, domain)) {
            String errorMessage = "certificate not for this host: " + domain;

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            sslSocket.getSession().invalidate();
            return new SslError(SslError.SSL_IDMISMATCH, currCertificate);
        }
    }

    //
    // first, we validate the chain using the standard validation
    // solution; if we do not find any errors, we are done; if we
    // fail the standard validation, we re-validate again below,
    // this time trying to retrieve any individual errors we can
    // report back to the user.
    //
    try {
        synchronized (mDefaultTrustManager) {
            mDefaultTrustManager.checkServerTrusted(serverCertificates, "RSA");

            // no errors!!!
            return null;
        }
    } catch (CertificateException e) {
        if (HttpLog.LOGV) {
            HttpLog.v("failed to pre-validate the certificate chain, error: " + e.getMessage());
        }
    }

    sslSocket.getSession().invalidate();

    SslError error = null;

    // we check the root certificate separately from the rest of the
    // chain; this is because we need to know what certificate in
    // the chain resulted in an error if any
    currCertificate = serverCertificates[serverCertificates.length - 1];
    if (currCertificate == null) {
        closeSocketThrowException(sslSocket, "root certificate is null");
    }

    // check if the last certificate in the chain (root) is trusted
    X509Certificate[] rootCertificateChain = { currCertificate };
    try {
        synchronized (mDefaultTrustManager) {
            mDefaultTrustManager.checkServerTrusted(rootCertificateChain, "RSA");
        }
    } catch (CertificateExpiredException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
            errorMessage = "root certificate has expired";
        }

        if (HttpLog.LOGV) {
            HttpLog.v(errorMessage);
        }

        error = new SslError(SslError.SSL_EXPIRED, currCertificate);
    } catch (CertificateNotYetValidException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
            errorMessage = "root certificate not valid yet";
        }

        if (HttpLog.LOGV) {
            HttpLog.v(errorMessage);
        }

        error = new SslError(SslError.SSL_NOTYETVALID, currCertificate);
    } catch (CertificateException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
            errorMessage = "root certificate not trusted";
        }

        if (HttpLog.LOGV) {
            HttpLog.v(errorMessage);
        }

        return new SslError(SslError.SSL_UNTRUSTED, currCertificate);
    }

    // Then go through the certificate chain checking that each
    // certificate trusts the next and that each certificate is
    // within its valid date range. Walk the chain in the order
    // from the CA to the end-user
    X509Certificate prevCertificate = serverCertificates[serverCertificates.length - 1];

    for (int i = serverCertificates.length - 2; i >= 0; --i) {
        currCertificate = serverCertificates[i];

        // if a certificate is null, we cannot verify the chain
        if (currCertificate == null) {
            closeSocketThrowException(sslSocket, "null certificate in the chain");
        }

        // verify if trusted by chain
        if (!prevCertificate.getSubjectDN().equals(currCertificate.getIssuerDN())) {
            String errorMessage = "not trusted by chain";

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            return new SslError(SslError.SSL_UNTRUSTED, currCertificate);
        }

        try {
            currCertificate.verify(prevCertificate.getPublicKey());
        } catch (GeneralSecurityException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "not trusted by chain";
            }

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            return new SslError(SslError.SSL_UNTRUSTED, currCertificate);
        }

        // verify if the dates are valid
        try {
            currCertificate.checkValidity();
        } catch (CertificateExpiredException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "certificate expired";
            }

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            if (error == null || error.getPrimaryError() < SslError.SSL_EXPIRED) {
                error = new SslError(SslError.SSL_EXPIRED, currCertificate);
            }
        } catch (CertificateNotYetValidException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "certificate not valid yet";
            }

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            if (error == null || error.getPrimaryError() < SslError.SSL_NOTYETVALID) {
                error = new SslError(SslError.SSL_NOTYETVALID, currCertificate);
            }
        }

        prevCertificate = currCertificate;
    }

    // if we do not have an error to report back to the user, throw
    // an exception (a generic error will be reported instead)
    if (error == null) {
        closeSocketThrowException(sslSocket,
                "failed to pre-validate the certificate chain due to a non-standard error");
    }

    return error;
}

From source file:org.ejbca.core.protocol.cmp.CrmfKeyUpdateHandler.java

@Override
/*//from  w w  w  .ja va 2s  .  c  o m
 * Handles the CMP message
 * 
 * Expects the CMP message to be a CrmfRequestMessage. The message is authenticated using 
 * EndEntityCertificateAuthenticationModule in client mode. It used the attached certificate 
 * to find then End Entity which this certificate belongs to and requesting for a new certificate 
 * to be generated. 
 * 
 * If automatic update of the key (same as certificate renewal), the end entity's status is set to 
 * 'NEW' before processing the request. If using the same old keys in the new certificate is not allowed, 
 * a check is made to insure the the key specified in the request is not the same as the key of the attached 
 * certificate.
 * 
 * The KeyUpdateRequet is processed only in client mode.
 */
public ResponseMessage handleMessage(final BaseCmpMessage msg, boolean authenticated) {
    if (LOG.isTraceEnabled()) {
        LOG.trace(">handleMessage");
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("CMP running on RA mode: " + this.cmpConfiguration.getRAMode(this.confAlias));
    }

    ResponseMessage resp = null;
    try {

        CrmfRequestMessage crmfreq = null;
        if (msg instanceof CrmfRequestMessage) {
            crmfreq = (CrmfRequestMessage) msg;
            crmfreq.getMessage();

            EndEntityCertificateAuthenticationModule eecmodule = null;
            X509Certificate oldCert = null;

            // Find the subjectDN to look for
            String subjectDN = null;
            String issuerDN = null;
            if (this.cmpConfiguration.getRAMode(this.confAlias)) {

                // Check that EndEntityCertificate authentication module is set
                if (!cmpConfiguration.isInAuthModule(confAlias,
                        CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE)) {
                    String errmsg = "EndEnityCertificate authentication module is not configured. For a KeyUpdate request to be authentication in RA mode, EndEntityCertificate "
                            + "authentication module has to be set and configured";
                    LOG.info(errmsg);
                    return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                            FailInfo.BAD_REQUEST, errmsg);
                }

                // Check PKIMessage authentication
                String authparameter = cmpConfiguration.getAuthenticationParameter(
                        CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE, confAlias);
                eecmodule = new EndEntityCertificateAuthenticationModule(admin, authparameter, confAlias,
                        cmpConfiguration, authenticated, caSession, certStoreSession, authorizationSession,
                        endEntityProfileSession, endEntityAccessSession, authenticationProviderSession,
                        endEntityManagementSession);
                if (!eecmodule.verifyOrExtract(crmfreq.getPKIMessage(), null)) {
                    LOG.info(eecmodule.getErrorMessage());
                    return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                            FailInfo.BAD_REQUEST, eecmodule.getErrorMessage());
                } else {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("The CMP KeyUpdate request for SubjectDN '" + crmfreq.getSubjectDN()
                                + "' was verified successfully");
                    }
                }
                oldCert = (X509Certificate) eecmodule.getExtraCert();

                CertReqMessages kur = (CertReqMessages) crmfreq.getPKIMessage().getBody().getContent();
                CertReqMsg certmsg;
                try {
                    certmsg = kur.toCertReqMsgArray()[0];
                } catch (Exception e) {
                    LOG.debug(
                            "Could not parse the revocation request. Trying to parse it as novosec generated message.");
                    certmsg = CmpMessageHelper.getNovosecCertReqMsg(kur);
                    LOG.debug("Succeeded in parsing the novosec generated request.");
                }
                X500Name dn = certmsg.getCertReq().getCertTemplate().getSubject();
                if (dn != null) {
                    subjectDN = dn.toString();
                }
                dn = certmsg.getCertReq().getCertTemplate().getIssuer();
                if (dn != null) {
                    issuerDN = dn.toString();
                }
            } else { // client mode

                eecmodule = new EndEntityCertificateAuthenticationModule(admin, null, confAlias,
                        cmpConfiguration, authenticated, caSession, certStoreSession, authorizationSession,
                        endEntityProfileSession, endEntityAccessSession, authenticationProviderSession,
                        endEntityManagementSession);
                if (!eecmodule.verifyOrExtract(crmfreq.getPKIMessage(), null)) {
                    LOG.info(eecmodule.getErrorMessage());
                    return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                            FailInfo.BAD_REQUEST, eecmodule.getErrorMessage());
                }
                oldCert = (X509Certificate) eecmodule.getExtraCert();

                subjectDN = oldCert.getSubjectDN().toString();
                issuerDN = oldCert.getIssuerDN().toString();
            }

            if (subjectDN == null) {
                final String errMsg = "Cannot find a SubjectDN in the request";
                LOG.info(errMsg);
                return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                        FailInfo.BAD_REQUEST, errMsg);
            }

            // Find the end entity that the certificate belongs to                
            if (LOG.isDebugEnabled()) {
                LOG.debug("Looking for an end entity with subjectDN: " + subjectDN);
            }
            EndEntityInformation userdata = null;
            if (issuerDN == null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("The CMP KeyUpdateRequest did not specify an issuer");
                }
                List<EndEntityInformation> userdataList = endEntityAccessSession.findUserBySubjectDN(admin,
                        subjectDN);
                if (userdataList.size() > 0) {
                    userdata = userdataList.get(0);
                }
                if (userdataList.size() > 1) {
                    LOG.warn("Multiple end entities with subject DN " + subjectDN
                            + " were found. This may lead to unexpected behavior.");
                }
            } else {
                List<EndEntityInformation> userdataList = endEntityAccessSession
                        .findUserBySubjectAndIssuerDN(admin, subjectDN, issuerDN);
                if (userdataList.size() > 0) {
                    userdata = userdataList.get(0);
                }
                if (userdataList.size() > 1) {
                    LOG.warn("Multiple end entities with subject DN " + subjectDN + " and issuer DN" + issuerDN
                            + " were found. This may lead to unexpected behavior.");
                }
            }

            if (userdata == null) {
                final String errMsg = INTRES.getLocalizedMessage("cmp.infonouserfordn", subjectDN);
                LOG.info(errMsg);
                return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                        FailInfo.BAD_MESSAGE_CHECK, errMsg);
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug("Found user '" + userdata.getUsername() + "'");
            }

            // The password that should be used to obtain the new certificate
            String password = StringUtils.isNotEmpty(userdata.getPassword()) ? userdata.getPassword()
                    : eecmodule.getAuthenticationString();

            // Set the appropriate parameters in the end entity
            userdata.setPassword(password);
            endEntityManagementSession.changeUser(admin, userdata, true);
            if (this.cmpConfiguration.getKurAllowAutomaticUpdate(this.confAlias)) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Setting the end entity status to 'NEW'. Username: " + userdata.getUsername());
                }

                endEntityManagementSession.setUserStatus(admin, userdata.getUsername(),
                        EndEntityConstants.STATUS_NEW);
            }

            // Set the appropriate parameters in the request
            crmfreq.setUsername(userdata.getUsername());
            crmfreq.setPassword(password);
            if (crmfreq.getHeader().getProtectionAlg() != null) {
                crmfreq.setPreferredDigestAlg(AlgorithmTools
                        .getDigestFromSigAlg(crmfreq.getHeader().getProtectionAlg().getAlgorithm().getId()));
            }

            // Check the public key, whether it is allowed to use the old keys or not.
            if (!this.cmpConfiguration.getKurAllowSameKey(this.confAlias)) {
                PublicKey certPublicKey = oldCert.getPublicKey();
                PublicKey requestPublicKey = crmfreq.getRequestPublicKey();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Not allowing update with same key, comparing keys.");
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("OldKey: " + certPublicKey.toString());
                        LOG.trace("NewKey: " + requestPublicKey.toString());
                    }
                }
                if (certPublicKey.equals(requestPublicKey)) {
                    final String errMsg = "Invalid key. The public key in the KeyUpdateRequest is the same as the public key in the existing end entity certificate";
                    LOG.info(errMsg);
                    return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                            FailInfo.BAD_MESSAGE_CHECK, errMsg);
                }
            }

            // Process the request
            resp = signSession.createCertificate(admin, crmfreq,
                    org.ejbca.core.protocol.cmp.CmpResponseMessage.class, userdata);

            if (resp == null) {
                final String errMsg = INTRES.getLocalizedMessage("cmp.errornullresp");
                LOG.info(errMsg);
                resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                        FailInfo.BAD_MESSAGE_CHECK, errMsg);
            }
        } else {
            final String errMsg = INTRES.getLocalizedMessage("cmp.errornocmrfreq");
            LOG.info(errMsg);
            resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                    FailInfo.BAD_MESSAGE_CHECK, errMsg);
        }

    } catch (AuthorizationDeniedException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (CADoesntExistsException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (UserDoesntFullfillEndEntityProfile e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (WaitingForApprovalException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (EjbcaException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (FinderException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (CesecoreException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (InvalidKeyException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info("Error while reading the public key of the extraCert attached to the CMP request");
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info("Error while reading the public key of the extraCert attached to the CMP request");
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (NoSuchProviderException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info("Error while reading the public key of the extraCert attached to the CMP request");
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (CertificateExtensionException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    }

    if (LOG.isTraceEnabled()) {
        LOG.trace("<handleMessage");
    }
    return resp;
}

From source file:org.dogtagpki.server.rest.UserService.java

/**
 * Adds a certificate to a user//from ww  w.  j  a va 2  s  .  c  om
 * <P>
 *
 * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/
 * ui/admin-protocol-definition.html#user-admin
 * <P>
 *
 * <ul>
 * <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under
 * users/groups)
 * </ul>
 */
@Override
public Response addUserCert(String userID, UserCertData userCertData) {

    if (userCertData == null)
        throw new BadRequestException("Certificate data is null.");

    // ensure that any low-level exceptions are reported
    // to the signed audit log and stored as failures
    try {
        if (userID == null) {
            log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID"));
            throw new BadRequestException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID", headers));
        }

        IUser user = userGroupManager.createUser(userID);

        String encoded = userCertData.getEncoded();

        // no cert is a success
        if (encoded == null) {
            auditAddUserCert(userID, userCertData, ILogger.SUCCESS);
            return createOKResponse();
        }

        // only one cert added per operation
        X509Certificate cert = null;

        // Base64 decode cert
        byte binaryCert[] = Cert.parseCertificate(encoded);

        try {
            cert = new X509CertImpl(binaryCert);

        } catch (CertificateException e) {
            CMS.debug("UserService: Submitted data is not an X.509 certificate: " + e);
            // ignore
        }

        if (cert == null) {
            // TODO: Remove this code. Importing PKCS #7 is not supported.

            // cert chain direction
            boolean assending = true;

            // could it be a pkcs7 blob?
            CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_IS_PK_BLOB"));

            try {
                CryptoManager manager = CryptoManager.getInstance();

                PKCS7 pkcs7 = new PKCS7(binaryCert);

                X509Certificate p7certs[] = pkcs7.getCertificates();

                if (p7certs.length == 0) {
                    CMS.debug("UserService: PKCS #7 data contains no certificates");
                    throw new BadRequestException("PKCS #7 data contains no certificates");
                }

                // fix for 370099 - cert ordering can not be assumed
                // find out the ordering ...

                // self-signed and alone? take it. otherwise test
                // the ordering
                if (p7certs[0].getSubjectDN().toString().equals(p7certs[0].getIssuerDN().toString())
                        && (p7certs.length == 1)) {
                    cert = p7certs[0];
                    CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_SINGLE_CERT_IMPORT"));

                } else if (p7certs[0].getIssuerDN().toString().equals(p7certs[1].getSubjectDN().toString())) {
                    cert = p7certs[0];
                    CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_CERT_CHAIN_ACEND_ORD"));

                } else if (p7certs[1].getIssuerDN().toString().equals(p7certs[0].getSubjectDN().toString())) {
                    assending = false;
                    CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_CERT_CHAIN_DESC_ORD"));
                    cert = p7certs[p7certs.length - 1];

                } else {
                    // not a chain, or in random order
                    CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_CERT_BAD_CHAIN"));
                    throw new BadRequestException(getUserMessage("CMS_USRGRP_SRVLT_CERT_ERROR", headers));
                }

                CMS.debug("UserService: "
                        + CMS.getLogMessage("ADMIN_SRVLT_CHAIN_STORED_DB", String.valueOf(p7certs.length)));

                int j = 0;
                int jBegin = 0;
                int jEnd = 0;

                if (assending == true) {
                    jBegin = 1;
                    jEnd = p7certs.length;
                } else {
                    jBegin = 0;
                    jEnd = p7certs.length - 1;
                }

                // store the chain into cert db, except for the user cert
                for (j = jBegin; j < jEnd; j++) {
                    CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_CERT_IN_CHAIN",
                            String.valueOf(j), String.valueOf(p7certs[j].getSubjectDN())));
                    org.mozilla.jss.crypto.X509Certificate leafCert = manager
                            .importCACertPackage(p7certs[j].getEncoded());

                    if (leafCert == null) {
                        CMS.debug("UserService: missing leaf certificate");
                        log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_LEAF_CERT_NULL"));
                    } else {
                        CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_LEAF_CERT_NON_NULL"));
                    }

                    if (leafCert instanceof InternalCertificate) {
                        ((InternalCertificate) leafCert).setSSLTrust(InternalCertificate.VALID_CA
                                | InternalCertificate.TRUSTED_CA | InternalCertificate.TRUSTED_CLIENT_CA);
                    } else {
                        log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NOT_INTERNAL_CERT",
                                String.valueOf(p7certs[j].getSubjectDN())));
                    }
                }

                /*
                } catch (CryptoManager.UserCertConflictException e) {
                // got a "user cert" in the chain, most likely the CA
                // cert of this instance, which has a private key.  Ignore
                log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_PKS7_IGNORED", e.toString()));
                */
            } catch (PKIException e) {
                CMS.debug("UserService: Unable to import user certificate from PKCS #7 data: " + e);
                log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_CERT_ERROR", e.toString()));
                throw e;

            } catch (Exception e) {
                CMS.debug(e);
                log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_CERT_ERROR", e.toString()));
                throw new PKIException("Unable to import user certificate from PKCS #7 data: " + e.getMessage(),
                        e);
            }
        }

        try {
            CMS.debug("UserService: " + CMS.getLogMessage("ADMIN_SRVLT_BEFORE_VALIDITY"));
            cert.checkValidity(); // throw exception if fails

            user.setX509Certificates(new X509Certificate[] { cert });
            userGroupManager.addUserCert(user);

            auditAddUserCert(userID, userCertData, ILogger.SUCCESS);

            // read the data back

            userCertData.setVersion(cert.getVersion());
            userCertData.setSerialNumber(new CertId(cert.getSerialNumber()));
            userCertData.setIssuerDN(cert.getIssuerDN().toString());
            userCertData.setSubjectDN(cert.getSubjectDN().toString());
            String certID = userCertData.getID();

            userCertData = getUserCertData(userID, URLEncoder.encode(certID, "UTF-8"));

            return createCreatedResponse(userCertData, userCertData.getLink().getHref());

        } catch (CertificateExpiredException e) {
            CMS.debug("UserService: Certificate expired: " + e);
            log(ILogger.LL_FAILURE,
                    CMS.getLogMessage("ADMIN_SRVLT_ADD_CERT_EXPIRED", String.valueOf(cert.getSubjectDN())));
            throw new BadRequestException("Certificate expired: " + e.getMessage(), e);

        } catch (CertificateNotYetValidException e) {
            CMS.debug("UserService: Certificate not yet valid: " + e);
            log(ILogger.LL_FAILURE,
                    CMS.getLogMessage("USRGRP_SRVLT_CERT_NOT_YET_VALID", String.valueOf(cert.getSubjectDN())));
            throw new BadRequestException("Certificate not yet valid: " + e.getMessage(), e);
        }

    } catch (PKIException e) {
        CMS.debug("UserService: Unable to import user certificate: " + e);
        auditAddUserCert(userID, userCertData, ILogger.FAILURE);
        throw e;

    } catch (Exception e) {
        CMS.debug(e);
        log(ILogger.LL_FAILURE, e.toString());
        auditAddUserCert(userID, userCertData, ILogger.FAILURE);
        throw new PKIException("Unable to import user certificate: " + e.getMessage(), e);
    }
}

From source file:com.viettel.hqmc.DAO.FilesDAO.java

public static OCSP.RevocationStatus.CertStatus checkRevocationStatus(X509Certificate peerCert,
        X509Certificate issuerCert) throws Exception {
    OCSPReq request = generateOCSPRequest2(issuerCert, peerCert.getSerialNumber());
    //This list will sometimes have non ocsp urls as well.
    List<String> locations = getAIALocations(peerCert);
    for (String serviceUrl : locations) {
        SingleResp[] responses;//from  w  w w . j  av  a  2s  .  com
        try {
            ResourceBundle rb = ResourceBundle.getBundle("config");
            //String host = rb.getString("ocspUrl");
            String BCY = rb.getString("BCY");
            String checkBCY = issuerCert.getIssuerDN().toString();
            String host;
            if (BCY.equals(checkBCY)) {
                host = rb.getString("ocspBcyUrl");
            } else {
                host = getOcspUrl(peerCert);
            }
            //String host = "http://ocsp.ca.gov.vn:2560";
            OCSPResp ocspResponse = getOCSPResponse(host, request);
            if (OCSPRespStatus.SUCCESSFUL != ocspResponse.getStatus()) {
                continue; // Server didn't give the response right.
            }
            BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject();
            responses = (basicResponse == null) ? null : basicResponse.getResponses();
            //todo use the super exception
        } catch (Exception ex) {
            LogUtil.addLog(ex);//binhnt sonar a160901
            continue;
        }
        if (responses != null && responses.length == 1) {
            SingleResp resp = responses[0];
            OCSP.RevocationStatus.CertStatus status = getRevocationStatus(resp);
            return status;
        }
    }
    throw new Exception("Cant get Revocation Status from OCSP.");
}