Example usage for java.security.cert CertificateException toString

List of usage examples for java.security.cert CertificateException toString

Introduction

In this page you can find the example usage for java.security.cert CertificateException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:EasyX509TrustManager.java

/**
 * @see com.sun.net.ssl.X509TrustManager#isServerTrusted(X509Certificate[])
 *//* ww  w  .  j a  v  a2  s .c  o  m*/
public boolean isServerTrusted(X509Certificate[] certificates) {
    if ((certificates != null) && LOG.isDebugEnabled()) {
        LOG.debug("Server certificate chain:");
        for (int i = 0; i < certificates.length; i++) {
            LOG.debug("X509Certificate[" + i + "]=" + certificates[i]);
        }
    }
    if ((certificates != null) && (certificates.length == 1)) {
        X509Certificate certificate = certificates[0];
        try {
            certificate.checkValidity();
        } catch (CertificateException e) {
            LOG.error(e.toString());
            return false;
        }
        return true;
    } else {
        return this.standardTrustManager.isServerTrusted(certificates);
    }
}

From source file:it.drwolf.ridire.session.ssl.EasyX509TrustManager.java

/**
 * @see com.sun.net.ssl.X509TrustManager#isServerTrusted(X509Certificate[])
 *//*from w  w w  .j a  va2s . co m*/
public boolean isServerTrusted(X509Certificate[] certificates) {
    if (certificates != null && LOG.isDebugEnabled()) {
        LOG.debug("Server certificate chain:");
        for (int i = 0; i < certificates.length; i++) {
            LOG.debug("X509Certificate[" + i + "]=" + certificates[i]);
        }
    }
    if (certificates != null && certificates.length == 1) {
        X509Certificate certificate = certificates[0];
        try {
            certificate.checkValidity();
        } catch (CertificateException e) {
            LOG.error(e.toString());
            return false;
        }
        return true;
    } else {
        return ((EasyX509TrustManager) this.standardTrustManager).isServerTrusted(certificates);
    }
}

From source file:ch.truesolutions.payit.https.EasyX509TrustManager.java

public boolean isServerTrusted(X509Certificate[] certificates) {
    if ((certificates != null) && LOG.isDebugEnabled()) {
        LOG.debug("Server certificate chain:");
        for (int i = 0; i < certificates.length; i++) {
            LOG.debug("X509Certificate[" + i + "]=" + certificates[i]);

            // DS validate the certificate
            X509Certificate certificate = certificates[i];
            try {
                certificate.checkValidity();
                /*/*from  www .j a  v  a 2 s  .  c om*/
                try {
                if(!keyStore.isCertificateEntry("paynet_"+i)) {
                 LOG.debug("Certificate not in key store! adding it...");
                 keyStore.setCertificateEntry("paynet_"+i,certificate);
                }
                } catch (KeyStoreException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                }
                */
            } catch (CertificateException e) {
                LOG.error(e.toString());
                return false;
            }

        }
        return true;
    } else {
        return false;
    }

    /*
    if ((certificates != null) && (certificates.length == 1)) {
    X509Certificate certificate = certificates[0];
    try {
        certificate.checkValidity(); 
    }
    catch (CertificateException e) {
        LOG.error(e.toString());
        return false;
    }
    return true;
    } else {
    return this.standardTrustManager.isServerTrusted(certificates);
    }
    */
}

From source file:com.vmware.identity.idm.ValidateUtil.java

/**
 * Validates that given certificate is <code>valid</code>.
 * clockTolerance - value of current clock tolerance in milliseconds
 * @throws IllegalArgumentException/*from   w ww.  ja  v a  2  s.co  m*/
 *            on validation failure
 */
public static void validateSolutionDetail(SolutionDetail fieldValue, String fieldName, long clockTolerance) {

    X509Certificate cert = fieldValue.getCertificate();
    ValidateUtil.validateNotNull(cert, "Solution user certificate");
    try {
        cert.checkValidity();
    } catch (CertificateException ex) {
        if (ex instanceof CertificateNotYetValidException) {
            // Check to see whether certificate is within clock tolerance
            // if so do not throw, cert passes the validation
            if (cert.getNotBefore().getTime() <= System.currentTimeMillis() + clockTolerance) {
                return;
            }
        }

        if (ex instanceof CertificateExpiredException) {
            // Check to see whether certificate is within clock tolerance
            // if so do not throw, cert passes the validation
            if (cert.getNotAfter().getTime() >= System.currentTimeMillis() - clockTolerance) {
                return;
            }
        }

        logAndThrow(String.format("'%s' certificate is invalid - " + "certificateException %s", fieldName,
                ex.toString()));
    }
}

From source file:com.aivarsda.certpinninglib.HttpsPinner.java

/**
 * Will go over all certificate chains of the given HttpsURLConnection and
 * validate each one./*from   w ww.  j  a  v a  2 s  .c  om*/
 * 
 * @param con HttpsURLConnection that needs to be pinned.
 */
private boolean validateTrustedPins(HttpsURLConnection con) {
    boolean isSrvTrusted = false;
    if (con != null) {
        try {
            Certificate[] certs = con.getServerCertificates();
            for (Certificate cert : certs) {
                // More info on X509Certificate -> http://www.ietf.org/rfc/rfc2459.txt
                if (cert instanceof X509Certificate) {
                    // Checking the certificate validity, if not valid - exception will be thrown.
                    ((X509Certificate) cert).checkValidity();

                    // Pinning the certificate against the trusted pins list.
                    boolean hasTrustedPin = false;
                    try {
                        hasTrustedPin = hasTrustedPin((X509Certificate) cert);
                        if (hasTrustedPin)
                            isSrvTrusted = true;
                    } catch (CertificateException e) {
                        Log.e(TAG, e.toString());
                    }

                    // Stop when the trusted pin is found
                    if (hasTrustedPin && _stopPinningWhenTrusdedFound)
                        break;
                }
            }
        } catch (SSLPeerUnverifiedException e) {
            Log.e(TAG, e.toString());
        } catch (CertificateExpiredException e1) {
            Log.e(TAG, e1.toString());
        } catch (CertificateNotYetValidException e1) {
            Log.e(TAG, e1.toString());
        }
    }

    return isSrvTrusted;
}

From source file:com.netscape.cms.servlet.connector.ConnectorServlet.java

/**
 * Process request/*w  ww.  j  a  v  a 2 s .c om*/
 * <P>
 *
 * (Certificate Request - all "agent" profile cert requests made through a connector)
 * <P>
 *
 * (Certificate Request Processed - all automated "agent" profile based cert acceptance made through a connector)
 * <P>
 *
 * <ul>
 * <li>signed.audit LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST used when a profile cert request is made (before
 * approval process)
 * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED used when a certificate request has just been
 * through the approval process
 * <li>signed.audit LOGGING_SIGNED_AUDIT_INTER_BOUNDARY_SUCCESS used when inter-CIMC_Boundary data transfer is
 * successful (this is used when data does not need to be captured)
 * </ul>
 *
 * @param source string containing source
 * @param sourceUserId string containing source user ID
 * @param msg PKI message
 * @param token the authentication token
 * @exception EBaseException an error has occurred
 * @return PKI message
 */
protected IPKIMessage processRequest(String source, String sourceUserId, IPKIMessage msg, IAuthToken token)
        throws EBaseException {
    String auditMessage = null;
    String auditSubjectID = sourceUserId;
    String auditProtectionMethod = SIGNED_AUDIT_PROTECTION_METHOD_SSL;
    String auditRequestType = msg.getReqType();
    String auditRequesterID = msg.getReqId();

    // additional parms for LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST
    String auditCertificateSubjectName = ILogger.SIGNED_AUDIT_EMPTY_VALUE;
    String subject = null;

    // "normalize" the "auditSubjectID"
    if (auditSubjectID != null) {
        auditSubjectID = auditSubjectID.trim();
    } else {
        auditSubjectID = ILogger.UNIDENTIFIED;
    }

    // "normalize" the "auditRequestType"
    if (auditRequestType != null) {
        auditRequestType = auditRequestType.trim();
    } else {
        auditRequestType = ILogger.SIGNED_AUDIT_EMPTY_VALUE;
    }

    // "normalize" the "auditRequesterID"
    if (auditRequesterID != null) {
        auditRequesterID = auditRequesterID.trim();
    } else {
        auditRequesterID = ILogger.UNIDENTIFIED;
    }

    IPKIMessage replymsg = null;

    try {
        IRequestQueue queue = mAuthority.getRequestQueue();
        String srcid = source + ":" + msg.getReqId();

        // find request in request queue and return result.
        RequestId thisreqid = queue.findRequestBySourceId(srcid);
        IRequest thisreq = null;

        if (thisreqid != null) {
            thisreq = queue.findRequest(thisreqid);
            if (thisreq == null) {
                // strange case.
                String errormsg = "Cannot find request in request queue " + thisreqid;

                mAuthority.log(ILogger.LL_FAILURE,
                        CMS.getLogMessage("CMSGW_REQUEST_ID_NOT_FOUND_1", thisreqid.toString()));

                // store a message in the signed audit log file
                auditMessage = CMS.getLogMessage(AuditEvent.INTER_BOUNDARY, auditSubjectID, ILogger.FAILURE,
                        auditProtectionMethod, auditRequestType, auditRequesterID);

                audit(auditMessage);

                // NOTE:  The signed audit event
                //        LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST
                //        does not yet matter at this point!

                throw new EBaseException(errormsg);
            } else {
                mAuthority.log(ILogger.LL_INFO, "Found request " + thisreqid + " for " + srcid);
                replymsg = CMS.getHttpPKIMessage();
                replymsg.fromRequest(thisreq);

                // store a message in the signed audit log file
                auditMessage = CMS.getLogMessage(AuditEvent.INTER_BOUNDARY, auditSubjectID, ILogger.SUCCESS,
                        auditProtectionMethod, auditRequestType, auditRequesterID);

                audit(auditMessage);

                // NOTE:  The signed audit event
                //        LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST
                //        does not yet matter at this point!

                return replymsg;
            }
        }

        // if not found process request.
        thisreq = queue.newRequest(msg.getReqType());
        CMS.debug("ConnectorServlet: created requestId=" + thisreq.getRequestId().toString());
        thisreq.setSourceId(srcid);

        // NOTE:  For the following signed audit message, since we only
        //        care about the "msg.toRequest( thisreq );" command, and
        //        since this command does not throw an EBaseException
        //        (which is the only exception designated by this method),
        //        then this code does NOT need to be contained within its
        //        own special try/catch block.
        msg.toRequest(thisreq);

        if (isProfileRequest(thisreq)) {
            X509CertInfo info = thisreq.getExtDataInCertInfo(IEnrollProfile.REQUEST_CERTINFO);

            try {
                CertificateSubjectName sn = (CertificateSubjectName) info.get(X509CertInfo.SUBJECT);

                // if the cert subject name is NOT MISSING, retrieve the
                // actual "auditCertificateSubjectName" and "normalize"
                // it
                if (sn != null) {
                    subject = sn.toString();
                    if (subject != null) {
                        // NOTE:  This is ok even if the cert subject
                        //        name is "" (empty)!
                        auditCertificateSubjectName = subject.trim();
                    }
                }

                // store a message in the signed audit log file
                auditMessage = CMS.getLogMessage(AuditEvent.PROFILE_CERT_REQUEST, auditSubjectID,
                        ILogger.SUCCESS, auditRequesterID, auditProfileID(), auditCertificateSubjectName);

                audit(auditMessage);
            } catch (CertificateException e) {
                CMS.debug("ConnectorServlet: processRequest " + e.toString());

                // store a message in the signed audit log file
                auditMessage = CMS.getLogMessage(AuditEvent.PROFILE_CERT_REQUEST, auditSubjectID,
                        ILogger.FAILURE, auditRequesterID, auditProfileID(), auditCertificateSubjectName);

                audit(auditMessage);
            } catch (IOException e) {
                CMS.debug("ConnectorServlet: processRequest " + e.toString());

                // store a message in the signed audit log file
                auditMessage = CMS.getLogMessage(AuditEvent.PROFILE_CERT_REQUEST, auditSubjectID,
                        ILogger.FAILURE, auditRequesterID, auditProfileID(), auditCertificateSubjectName);

                audit(auditMessage);
            }
        }

        thisreq.setExtData(IRequest.AUTH_TOKEN, token);

        if (StringUtils.isNotEmpty(msg.getReqRealm())) {
            thisreq.setRealm(msg.getReqRealm());
        }

        // setting requestor type must come after copy contents. because
        // requestor is a regular attribute.
        thisreq.setExtData(IRequest.REQUESTOR_TYPE, IRequest.REQUESTOR_RA);
        mAuthority.log(ILogger.LL_INFO, "Processing remote request " + srcid);

        // Set this so that request's updateBy is recorded
        SessionContext s = SessionContext.getContext();

        if (s.get(SessionContext.USER_ID) == null) {
            s.put(SessionContext.USER_ID, sourceUserId);
        }

        if (s.get(SessionContext.REQUESTER_ID) == null) {
            s.put(SessionContext.REQUESTER_ID, msg.getReqId());
        }

        //CMS.debug("ConnectorServlet: calling processRequest instance=" +
        //        thisreq);
        if (isProfileRequest(thisreq)) {
            normalizeProfileRequest(thisreq);
        }

        CMS.debug("ConnectorServlet: calling processRequest");
        try {
            queue.processRequest(thisreq);

        } finally {

            if (isProfileRequest(thisreq)) {

                X509CertImpl x509cert = thisreq.getExtDataInCert(IEnrollProfile.REQUEST_ISSUED_CERT);

                if (x509cert != null) {

                    audit(CertRequestProcessedEvent.createSuccessEvent(auditSubjectID, auditRequesterID,
                            ILogger.SIGNED_AUDIT_ACCEPTANCE, x509cert));

                } else {

                    audit(CertRequestProcessedEvent.createFailureEvent(auditSubjectID, auditRequesterID,
                            ILogger.SIGNED_AUDIT_REJECTION, ILogger.SIGNED_AUDIT_EMPTY_VALUE));
                }
            }
        }

        replymsg = CMS.getHttpPKIMessage();
        replymsg.fromRequest(thisreq);

        CMS.debug("ConnectorServlet: replymsg.reqStatus=" + replymsg.getReqStatus());

        //for audit log
        String agentID = sourceUserId;
        String initiative = AuditFormat.FROMRA + " trustedManagerID: " + agentID + " remote reqID "
                + msg.getReqId();
        String authMgr = AuditFormat.NOAUTH;

        if (token != null) {
            authMgr = token.getInString(AuthToken.TOKEN_AUTHMGR_INST_NAME);
        }

        if (isProfileRequest(thisreq)) {
            // XXX audit log
            CMS.debug("ConnectorServlet: done requestId=" + thisreq.getRequestId().toString());

            // store a message in the signed audit log file
            auditMessage = CMS.getLogMessage(AuditEvent.INTER_BOUNDARY, auditSubjectID, ILogger.SUCCESS,
                    auditProtectionMethod, auditRequestType, auditRequesterID);

            audit(auditMessage);

            // NOTE:  The signed audit event
            //        LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST
            //        has already been logged at this point!

            return replymsg;
        }

        // Get the certificate info from the request
        X509CertInfo x509Info[] = thisreq.getExtDataInCertInfoArray(IRequest.CERT_INFO);

        try {
            if (!thisreq.getRequestStatus().equals(RequestStatus.COMPLETE)) {
                if (x509Info != null) {
                    for (int i = 0; i < x509Info.length; i++) {
                        mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER, AuditFormat.LEVEL, AuditFormat.FORMAT,
                                new Object[] { thisreq.getRequestType(), thisreq.getRequestId(), initiative,
                                        authMgr, thisreq.getRequestStatus(),
                                        x509Info[i].get(X509CertInfo.SUBJECT), "" });
                    }
                } else {
                    mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER, AuditFormat.LEVEL, AuditFormat.NODNFORMAT,
                            new Object[] { thisreq.getRequestType(), thisreq.getRequestId(), initiative,
                                    authMgr, thisreq.getRequestStatus() });
                }
            } else {
                if (thisreq.getRequestType().equals(IRequest.ENROLLMENT_REQUEST)) {
                    // XXX make the repeat record.
                    // Get the certificate(s) from the request
                    X509CertImpl x509Certs[] = null;

                    if (x509Info != null)
                        x509Certs = thisreq.getExtDataInCertArray(IRequest.ISSUED_CERTS);

                    // return potentially more than one certificates.
                    if (x509Certs != null) {
                        for (int i = 0; i < x509Certs.length; i++) {
                            mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER, AuditFormat.LEVEL,
                                    AuditFormat.FORMAT,
                                    new Object[] { thisreq.getRequestType(), thisreq.getRequestId(), initiative,
                                            authMgr, "completed", x509Certs[i].getSubjectDN(),
                                            "cert issued serial number: 0x"
                                                    + x509Certs[i].getSerialNumber().toString(16) });
                        }
                    } else {
                        mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER, AuditFormat.LEVEL,
                                AuditFormat.NODNFORMAT, new Object[] { thisreq.getRequestType(),
                                        thisreq.getRequestId(), initiative, authMgr, "completed" });
                    }
                } else if (thisreq.getRequestType().equals(IRequest.RENEWAL_REQUEST)) {
                    X509CertImpl[] certs = thisreq.getExtDataInCertArray(IRequest.OLD_CERTS);
                    X509CertImpl old_cert = certs[0];

                    certs = thisreq.getExtDataInCertArray(IRequest.ISSUED_CERTS);
                    X509CertImpl renewed_cert = certs[0];

                    if (old_cert != null && renewed_cert != null) {
                        mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER, AuditFormat.LEVEL,
                                AuditFormat.RENEWALFORMAT,
                                new Object[] { thisreq.getRequestId(), initiative, authMgr, "completed",
                                        old_cert.getSubjectDN(), old_cert.getSerialNumber().toString(16),
                                        "new serial number: 0x"
                                                + renewed_cert.getSerialNumber().toString(16) });
                    } else {
                        mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER, AuditFormat.LEVEL,
                                AuditFormat.NODNFORMAT, new Object[] { thisreq.getRequestType(),
                                        thisreq.getRequestId(), initiative, authMgr, "completed with error" });
                    }
                } else if (thisreq.getRequestType().equals(IRequest.REVOCATION_REQUEST)) {
                    Certificate[] oldCerts = thisreq.getExtDataInCertArray(IRequest.OLD_CERTS);
                    RevokedCertImpl crlentries[] = thisreq.getExtDataInRevokedCertArray(IRequest.REVOKED_CERTS);
                    CRLExtensions crlExts = crlentries[0].getExtensions();
                    int reason = 0;

                    if (crlExts != null) {
                        Enumeration<Extension> enum1 = crlExts.getElements();

                        while (enum1.hasMoreElements()) {
                            Extension ext = enum1.nextElement();

                            if (ext instanceof CRLReasonExtension) {
                                reason = ((CRLReasonExtension) ext).getReason().toInt();
                                break;
                            }
                        }
                    }

                    int count = oldCerts.length;
                    Integer result = thisreq.getExtDataInInteger(IRequest.RESULT);

                    if (result.equals(IRequest.RES_ERROR)) {
                        String[] svcErrors = thisreq.getExtDataInStringArray(IRequest.SVCERRORS);

                        if (svcErrors != null && svcErrors.length > 0) {
                            for (int i = 0; i < svcErrors.length; i++) {
                                String err = svcErrors[i];

                                if (err != null) {
                                    for (int j = 0; j < count; j++) {
                                        if (oldCerts[j] != null) {
                                            if (oldCerts[j] instanceof X509CertImpl) {
                                                X509CertImpl cert = (X509CertImpl) oldCerts[j];

                                                mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
                                                        AuditFormat.LEVEL, AuditFormat.DOREVOKEFORMAT,
                                                        new Object[] { thisreq.getRequestId(), initiative,
                                                                "completed with error: " + err,
                                                                cert.getSubjectDN(),
                                                                cert.getSerialNumber().toString(16),
                                                                RevocationReason.fromInt(reason).toString() });
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        // the success.
                        for (int j = 0; j < count; j++) {
                            if (oldCerts[j] != null) {
                                if (oldCerts[j] instanceof X509CertImpl) {
                                    X509CertImpl cert = (X509CertImpl) oldCerts[j];

                                    mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER, AuditFormat.LEVEL,
                                            AuditFormat.DOREVOKEFORMAT,
                                            new Object[] { thisreq.getRequestId(), initiative, "completed",
                                                    cert.getSubjectDN(), cert.getSerialNumber().toString(16),
                                                    RevocationReason.fromInt(reason).toString() });
                                }
                            }
                        }
                    }
                } else {
                    mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER, AuditFormat.LEVEL, AuditFormat.NODNFORMAT,
                            new Object[] { thisreq.getRequestType(), thisreq.getRequestId(), initiative,
                                    authMgr, "completed" });
                }
            }

            // store a message in the signed audit log file
            auditMessage = CMS.getLogMessage(AuditEvent.INTER_BOUNDARY, auditSubjectID, ILogger.SUCCESS,
                    auditProtectionMethod, auditRequestType, auditRequesterID);

            audit(auditMessage);
        } catch (IOException e) {
            CMS.debug("ConnectorServlet: process " + e.toString());

            // store a message in the signed audit log file
            auditMessage = CMS.getLogMessage(AuditEvent.INTER_BOUNDARY, auditSubjectID, ILogger.FAILURE,
                    auditProtectionMethod, auditRequestType, auditRequesterID);

            audit(auditMessage);
        } catch (CertificateException e) {
            CMS.debug("ConnectorServlet: process " + e.toString());

            // store a message in the signed audit log file
            auditMessage = CMS.getLogMessage(AuditEvent.INTER_BOUNDARY, auditSubjectID, ILogger.FAILURE,
                    auditProtectionMethod, auditRequestType, auditRequesterID);

            audit(auditMessage);
        } catch (Exception e) {
            CMS.debug("ConnectorServlet: process " + e.toString());

            // store a message in the signed audit log file
            auditMessage = CMS.getLogMessage(AuditEvent.INTER_BOUNDARY, auditSubjectID, ILogger.FAILURE,
                    auditProtectionMethod, auditRequestType, auditRequesterID);

            audit(auditMessage);
        } finally {
            SessionContext.releaseContext();
        }

        // NOTE:  The signed audit event
        //        LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST
        //        has already been logged at this point!

        return replymsg;
    } catch (EBaseException e) {
        // store a message in the signed audit log file
        auditMessage = CMS.getLogMessage(AuditEvent.INTER_BOUNDARY, auditSubjectID, ILogger.FAILURE,
                auditProtectionMethod, auditRequestType, auditRequesterID);

        audit(auditMessage);

        // NOTE:  The signed audit event
        //        LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST
        //        has either already been logged, or
        //        does not yet matter at this point!

        return replymsg;
    }
}

From source file:com.netscape.ca.CertificateAuthority.java

/**
 * init CA signing unit & cert chain.
 *//*from ww  w .  j a v a  2 s.  c o  m*/
private synchronized void initSigUnit() throws EBaseException {

    // init signing unit
    mSigningUnit = new SigningUnit();
    IConfigStore caSigningCfg = mConfig.getSubStore(PROP_SIGNING_SUBSTORE);

    try {
        String caSigningCertStr = caSigningCfg.getString("cert", "");
        if (caSigningCertStr.equals("")) {
            logger.debug("CertificateAuthority: CA signing cert not found");

        } else {
            logger.debug("CertificateAuthority: CA signing cert: " + caSigningCertStr);

            byte[] bytes = Utils.base64decode(caSigningCertStr);
            logger.debug("CertificateAuthority: size: " + bytes.length + " bytes");

            mCaCert = new X509CertImpl(bytes);

            // this ensures the isserDN and subjectDN have the same encoding
            // as that of the CA signing cert
            mSubjectObj = mCaCert.getSubjectObj();
            logger.debug("CertificateAuthority: subject DN: " + mSubjectObj);

            // this mIssuerObj is the "issuerDN" obj for the certs this CA
            // issues, NOT necessarily the isserDN obj of the CA signing cert
            mIssuerObj = new CertificateIssuerName((X500Name) mSubjectObj.get(CertificateIssuerName.DN_NAME));
            logger.debug("CertificateAuthority: issuer DN: " + mIssuerObj);
        }

    } catch (CertificateException e) {
        logger.error("Unable to initialize signing unit: " + e.getMessage(), e);
        log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_OCSP_CHAIN", e.toString()));
        throw new ECAException(CMS.getUserMessage("CMS_CA_BUILD_CA_CHAIN_FAILED", e.toString()), e);

    } catch (IOException e) {
        logger.error("Unable to initialize signing unit: " + e.getMessage(), e);
        log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_OCSP_CHAIN", e.toString()));
        throw new ECAException(CMS.getUserMessage("CMS_CA_BUILD_CA_CHAIN_FAILED", e.toString()), e);
    }

    mSigningUnit.init(this, caSigningCfg, mNickname);
    hasKeys = true;
    signingUnitException = null;
    logger.debug("CA signing unit inited");

    try {
        // for identrus
        IConfigStore CrlStore = mConfig.getSubStore(PROP_CRL_SIGNING_SUBSTORE);

        if (isHostAuthority() && CrlStore != null && CrlStore.size() > 0) {
            mCRLSigningUnit = new SigningUnit();
            mCRLSigningUnit.init(this, mConfig.getSubStore(PROP_CRL_SIGNING_SUBSTORE));
        } else {
            mCRLSigningUnit = mSigningUnit;
        }

        // init cert chain
        CryptoManager manager = CryptoManager.getInstance();

        int caChainNum = caSigningCfg.getInteger(PROP_CA_CHAIN_NUM, 0);
        logger.debug("CertificateAuthority: cachainNum: " + caChainNum);

        if (caChainNum > 0) {

            logger.debug("CertificateAuthority: create cert chain from files:");

            IConfigStore chainStore = caSigningCfg.getSubStore(PROP_CA_CHAIN);

            if (chainStore == null) {
                log(ILogger.LL_FAILURE,
                        CMS.getLogMessage("CMSCORE_CA_CA_OCSP_CHAIN", "ca cert chain config error"));
                throw new ECAException(
                        CMS.getUserMessage("CMS_CA_BUILD_CA_CHAIN_FAILED", "ca cert chain config error"));
            }

            java.security.cert.X509Certificate[] implchain = new java.security.cert.X509Certificate[caChainNum];

            for (int i = 0; i < caChainNum; i++) {
                String subtreeName = PROP_CA_CERT + i;

                // cert file name must be full path
                String certFileName = chainStore.getString(subtreeName, null);
                logger.debug(" - file: " + certFileName);

                if ((certFileName == null) || certFileName.equals("")) {
                    log(ILogger.LL_FAILURE,
                            CMS.getLogMessage("CMSCORE_CA_CA_OCSP_CHAIN", "cert file config error"));
                    throw new ECAException(
                            CMS.getUserMessage("CMS_CA_BUILD_CA_CHAIN_FAILED", "cert file config error"));
                }

                byte[] b64Bytes = getCertFromFile(certFileName);
                String b64String = new String(b64Bytes);
                byte[] certBytes = KeyCertUtil.convertB64EToByteArray(b64String);

                implchain[i] = new X509CertImpl(certBytes);
            }

            mCACertChain = new CertificateChain(implchain);

        } else {

            logger.debug("CertificateAuthority: create cert chain from certs in NSS database");

            org.mozilla.jss.crypto.X509Certificate caCert = mSigningUnit.getCert();
            logger.debug("CertificateAuthority: CA cert: " + caCert.getSubjectDN());

            org.mozilla.jss.crypto.X509Certificate[] chain = manager.buildCertificateChain(caCert);

            // do this in case other subsyss expect a X509CertImpl
            java.security.cert.X509Certificate[] implchain = new java.security.cert.X509Certificate[chain.length];

            for (int i = 0; i < chain.length; i++) {
                implchain[i] = new X509CertImpl(chain[i].getEncoded());
                logger.debug("CertificateAuthority: CA cert: " + caCert.getSubjectDN());
            }

            mCACertChain = new CertificateChain(implchain);
        }

        logger.debug("CertificateAuthority: cert chain created");

        IConfigStore OCSPStore = mConfig.getSubStore(PROP_OCSP_SIGNING_SUBSTORE);

        if (isHostAuthority() && OCSPStore != null && OCSPStore.size() > 0) {
            mOCSPSigningUnit = new SigningUnit();
            mOCSPSigningUnit.init(this, mConfig.getSubStore(PROP_OCSP_SIGNING_SUBSTORE));
            logger.debug("Separate OCSP signing unit inited");
        } else {
            mOCSPSigningUnit = mSigningUnit;
            logger.debug("Shared OCSP signing unit inited");
        }

        org.mozilla.jss.crypto.X509Certificate[] ocspChain = manager
                .buildCertificateChain(mOCSPSigningUnit.getCert());
        // do this in case other subsyss expect a X509CertImpl
        java.security.cert.X509Certificate[] ocspImplchain = new java.security.cert.X509Certificate[ocspChain.length];

        for (int i = 0; i < ocspChain.length; i++) {
            ocspImplchain[i] = new X509CertImpl(ocspChain[i].getEncoded());
        }
        mOCSPCertChain = new CertificateChain(ocspImplchain);
        logger.debug("in init - got OCSP chain from JSS.");

        mCaX509Cert = mSigningUnit.getCert();
        mCaCert = new X509CertImpl(mCaX509Cert.getEncoded());
        getCASigningAlgorithms();
        mSubjectObj = mCaCert.getSubjectObj();
        if (mSubjectObj != null) {
            // this ensures the isserDN and subjectDN have the same encoding
            // as that of the CA signing cert
            logger.debug("CertificateAuthority: initSigUnit - setting mIssuerObj and mSubjectObj");
            // this mIssuerObj is the "issuerDN" obj for the certs this CA
            // issues, NOT necessarily the isserDN obj of the CA signing cert
            // unless the CA is self-signed
            mIssuerObj = new CertificateIssuerName((X500Name) mSubjectObj.get(CertificateIssuerName.DN_NAME));
        }
        mName = (X500Name) mCaCert.getSubjectDN();

        mCRLX509Cert = mCRLSigningUnit.getCert();
        mCRLCert = new X509CertImpl(mCRLX509Cert.getEncoded());
        mCRLName = (X500Name) mCRLCert.getSubjectDN();

        mOCSPX509Cert = mOCSPSigningUnit.getCert();
        mOCSPNickname = mOCSPSigningUnit.getNickname();
        mOCSPCert = new X509CertImpl(mOCSPX509Cert.getEncoded());
        mOCSPName = (X500Name) mOCSPCert.getSubjectDN();
        mNickname = mSigningUnit.getNickname();
        logger.debug("in init - got CA name " + mName);

    } catch (NotInitializedException e) {
        log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_OCSP_SIGNING", e.toString()));
        throw new ECAException(CMS.getUserMessage("CMS_CA_CRYPTO_NOT_INITIALIZED"), e);

    } catch (CertificateException e) {
        logger.error("Unable to build cert chain: " + e.getMessage(), e);
        log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_OCSP_CHAIN", e.toString()));
        throw new ECAException(CMS.getUserMessage("CMS_CA_BUILD_CA_CHAIN_FAILED", e.toString()), e);

    } catch (FileNotFoundException e) {
        logger.error("Unable to build cert chain: " + e.getMessage(), e);
        log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_OCSP_CHAIN", e.toString()));
        throw new ECAException(CMS.getUserMessage("CMS_CA_BUILD_CA_CHAIN_FAILED", e.toString()), e);

    } catch (IOException e) {
        logger.error("Unable to build cert chain: " + e.getMessage(), e);
        log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_OCSP_CHAIN", e.toString()));
        throw new ECAException(CMS.getUserMessage("CMS_CA_BUILD_CA_CHAIN_FAILED", e.toString()), e);

    } catch (TokenException e) {
        logger.error("Unable to build cert chain: " + e.getMessage(), e);
        log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_OCSP_CHAIN", e.toString()));
        throw new ECAException(CMS.getUserMessage("CMS_CA_BUILD_CA_CHAIN_FAILED", e.toString()), e);
    }

    generateSigningInfoAuditEvents();
}

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

/**
 * Adds a certificate to a user//from w  w  w. java 2  s .com
 * <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:org.dspace.authenticate.X509Authentication.java

/**
 * Verify CERTIFICATE against KEY. Return true if and only if CERTIFICATE is
 * valid and can be verified against KEY.
 *
 * @param context/*from   ww  w.  j  a  va 2 s.  co m*/
 *            The current DSpace context
 * @param certificate -
 *            An X509 certificate object
 * @return - True if CERTIFICATE is valid and can be verified against KEY,
 *         false otherwise.
 */
private static boolean isValid(Context context, X509Certificate certificate) {
    if (certificate == null) {
        return false;
    }

    // This checks that current time is within cert's validity window:
    try {
        certificate.checkValidity();
    } catch (CertificateException e) {
        log.info(LogManager.getHeader(context, "authentication",
                "X.509 Certificate is EXPIRED or PREMATURE: " + e.toString()));
        return false;
    }

    // Try CA public key, if available.
    if (caPublicKey != null) {
        try {
            certificate.verify(caPublicKey);
            return true;
        } catch (GeneralSecurityException e) {
            log.info(LogManager.getHeader(context, "authentication",
                    "X.509 Certificate FAILED SIGNATURE check: " + e.toString()));
        }
    }

    // Try it with keystore, if available.
    if (caCertKeyStore != null) {
        try {
            Enumeration ke = caCertKeyStore.aliases();

            while (ke.hasMoreElements()) {
                String alias = (String) ke.nextElement();
                if (caCertKeyStore.isCertificateEntry(alias)) {
                    Certificate ca = caCertKeyStore.getCertificate(alias);
                    try {
                        certificate.verify(ca.getPublicKey());
                        return true;
                    } catch (CertificateException ce) {
                    }
                }
            }
            log.info(LogManager.getHeader(context, "authentication",
                    "Keystore method FAILED SIGNATURE check on client cert."));
        } catch (GeneralSecurityException e) {
            log.info(LogManager.getHeader(context, "authentication",
                    "X.509 Certificate FAILED SIGNATURE check: " + e.toString()));
        }

    }
    return false;
}

From source file:org.jivesoftware.sparkimpl.updater.EasyX509TrustManager.java

public boolean isServerTrusted(X509Certificate[] certificates) {
    if ((certificates != null) && LOG.isDebugEnabled()) {
        LOG.debug("Server certificate chain:");
        for (int i = 0; i < certificates.length; i++) {
            LOG.debug("X509Certificate[" + i + "]=" + certificates[i]);
        }//  w  w w . j av a 2 s .  c o  m
    }
    if ((certificates != null) && (certificates.length == 1)) {
        X509Certificate certificate = certificates[0];
        try {
            certificate.checkValidity();
        } catch (CertificateException e) {
            LOG.error(e.toString());
            return false;
        }
        return true;
    } else {
        try {
            this.standardTrustManager.checkServerTrusted(certificates, null);
            return true;
        } catch (CertificateException e) {
            return false;
        }
    }
}