Example usage for java.security.cert CertificateException getMessage

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

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java

/** @return a list of trusted signers or CAs */
@Deprecated //This method is only used for upgrading to version 6
private List<InternalKeyBindingTrustEntry> getOcspKeyBindingTrustDefaults() {
    // Import certificates used to verify OCSP request signatures and add these to each OcspKeyBinding's trust-list
    //  ocsp.signtrustdir=signtrustdir
    //  ocsp.signtrustvalidtime should be ignored
    final List<InternalKeyBindingTrustEntry> trustedCertificateReferences = new ArrayList<InternalKeyBindingTrustEntry>();
    if (OcspConfiguration.getEnforceRequestSigning() && OcspConfiguration.getRestrictSignatures()) {
        // Import certificates and configure Issuer+serialnumber in trustlist for each
        final String dirName = OcspConfiguration.getSignTrustDir();
        if (dirName != null) {
            final File directory = new File(dirName);
            if (directory.isDirectory()) {
                for (final File file : directory.listFiles()) {
                    try {
                        final List<Certificate> chain = CertTools.getCertsFromPEM(new FileInputStream(file));
                        if (!chain.isEmpty()) {
                            final String issuerDn = CertTools.getIssuerDN(chain.get(0));
                            final String subjectDn = CertTools.getSubjectDN(chain.get(0));
                            if (OcspConfiguration
                                    .getRestrictSignaturesByMethod() == OcspConfiguration.RESTRICTONSIGNER) {
                                final int caId = issuerDn.hashCode();
                                final BigInteger serialNumber = CertTools.getSerialNumber(chain.get(0));
                                if (!caSession.existsCa(caId)) {
                                    log.warn("Trusted certificate with serialNumber "
                                            + serialNumber.toString(16)
                                            + " is issued by an unknown CA with subject '" + issuerDn
                                            + "'. You should import this CA certificate as en external CA to make it known to the system.");
                                }//from w  w  w.j  a  v  a  2 s. c  o  m
                                trustedCertificateReferences
                                        .add(new InternalKeyBindingTrustEntry(caId, serialNumber));
                            } else {
                                final int caId = subjectDn.hashCode();
                                if (!caSession.existsCa(caId)) {
                                    log.warn("Trusted CA certificate with with subject '" + subjectDn
                                            + "' should be imported as en external CA to make it known to the system.");
                                }
                                trustedCertificateReferences.add(new InternalKeyBindingTrustEntry(caId, null));
                            }
                        }
                    } catch (CertificateException e) {
                        log.warn(e.getMessage());
                    } catch (FileNotFoundException e) {
                        log.warn(e.getMessage());
                    }
                }
            }
        }
    }
    return trustedCertificateReferences;
}

From source file:eu.eidas.auth.engine.EIDASSAMLEngine.java

/**
 * Gets the country from X.509 Certificate.
 * /*from   w ww.  jav  a  2s  .  c o  m*/
 * @param keyInfo the key info
 * 
 * @return the country
 */
private String getCountry(final KeyInfo keyInfo) {
    LOG.trace("Recover country information.");

    String result = "";
    try {
        final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0)
                .getX509Certificates().get(0);

        // Transform the KeyInfo to X509Certificate.
        CertificateFactory certFact;
        certFact = CertificateFactory.getInstance("X.509");

        final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue()));

        final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis);

        String distName = cert.getSubjectDN().toString();

        distName = StringUtils.deleteWhitespace(StringUtils.upperCase(distName));

        final String countryCode = "C=";
        final int init = distName.indexOf(countryCode);

        if (init > StringUtils.INDEX_NOT_FOUND) {
            // Exist country code.
            int end = distName.indexOf(',', init);

            if (end <= StringUtils.INDEX_NOT_FOUND) {
                end = distName.length();
            }

            if (init < end && end > StringUtils.INDEX_NOT_FOUND) {
                result = distName.substring(init + countryCode.length(), end);
                //It must be a two characters value
                if (result.length() > 2) {
                    result = result.substring(0, 2);
                }
            }
        }

    } catch (CertificateException e) {
        LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getCountry from certificate. {}", e.getMessage());
        LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getCountry from certificate. {}", e);
    }
    return result.trim();
}

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

/**
 * Dumps a certificate (cvc or x.509) to string format, suitable for manual inspection/debugging.
 * /*from w  w w.j av  a2  s . com*/
 * @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.cesecore.util.CertTools.java

/**
 * Gets subject or issuer DN in the format we are sure about (BouncyCastle),supporting UTF8.
 * //from w  ww  .j  ava  2  s  .  c o m
 * @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.netscape.ca.CertificateAuthority.java

public X509CertImpl getCACert() throws EBaseException {

    if (mCaCert != null) {
        return mCaCert;
    }/* ww w  .ja  v  a 2 s.c  om*/

    String cert = mConfig.getString("signing.cert");
    logger.debug("CertificateAuthority: CA signing cert: " + cert);

    if (StringUtils.isEmpty(cert)) {
        logger.error("CertificateAuthority: Missing CA signing certificate");
        throw new EBaseException("Missing CA signing certificate");
    }

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

    try {
        return new X509CertImpl(bytes);

    } catch (CertificateException e) {
        logger.error("Unable to parse CA signing cert: " + e.getMessage(), e);
        throw new EBaseException(e);
    }
}

From source file:ch.cyberduck.ui.cocoa.controller.BrowserController.java

@Action
public void securityLabelClicked(final ID sender) {
    final List<X509Certificate> certificates = Arrays
            .asList(pool.getFeature(X509TrustManager.class).getAcceptedIssuers());
    try {/* ww  w  .  j a v  a 2  s . c  om*/
        CertificateStoreFactory.get(this).display(certificates);
    } catch (CertificateException e) {
        log.warn(String.format("Failure decoding certificate %s", e.getMessage()));
    }
}

From source file:ch.cyberduck.ui.cocoa.BrowserController.java

@Action
public void securityLabelClicked(final ID sender) {
    if (session instanceof SSLSession) {
        final SSLSession<?> secured = (SSLSession) session;
        final List<X509Certificate> certificates = secured.getAcceptedIssuers();
        try {/*from w  ww  . j  a v a2 s  .com*/
            CertificateStoreFactory.get(this).display(certificates);
        } catch (CertificateException e) {
            log.warn(String.format("Failure decoding certificate %s", e.getMessage()));
        }
    }
}

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

/**
 * init CA signing unit & cert chain.
 *//*from w ww .  j a  v a2s .co  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.hyperic.util.security.DatabaseSSLProviderImpl.java

private X509TrustManager getCustomTrustManager(final X509TrustManager defaultTrustManager,
        final KeystoreConfig keystoreConfig, final boolean acceptUnverifiedCertificates,
        final KeyStore trustStore) {
    return new X509TrustManager() {
        private final Log log = LogFactory.getLog(X509TrustManager.class);

        public X509Certificate[] getAcceptedIssuers() {
            return defaultTrustManager.getAcceptedIssuers();
        }//from ww  w  .  j  a  va 2s . c o  m

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            try {
                defaultTrustManager.checkServerTrusted(chain, authType);
            } catch (CertificateException e) {
                CertificateExpiredException expiredCertException = getCertExpiredException(e);
                if (expiredCertException != null) {
                    log.error("Fail the connection because received certificate is expired. "
                            + "Please update the certificate.", expiredCertException);
                    throw new CertificateException(e);
                }
                if (acceptUnverifiedCertificates) {
                    log.info("Import the certification. (Received certificate is not trusted by keystore)");
                    importCertificate(chain);
                } else {
                    log.warn(
                            "Fail the connection because received certificate is not trusted by keystore: alias="
                                    + keystoreConfig.getAlias() + ", path=" + keystoreConfig.getFilePath());
                    log.debug(
                            "Fail the connection because received certificate is not trusted by keystore: alias="
                                    + keystoreConfig.getAlias() + ", path=" + keystoreConfig.getFilePath()
                                    + ", acceptUnverifiedCertificates=" + acceptUnverifiedCertificates,
                            e);
                    throw new CertificateException(e);
                }
            }
        }

        private CertificateExpiredException getCertExpiredException(Exception e) {
            while (e != null) {
                if (e instanceof CertificateExpiredException) {
                    return (CertificateExpiredException) e;
                }
                e = (Exception) e.getCause();
            }
            return null;
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            defaultTrustManager.checkClientTrusted(chain, authType);
        }

        private void importCertificate(X509Certificate[] chain) throws CertificateException {
            FileOutputStream keyStoreFileOutputStream = null;
            boolean hasLock = false;
            final boolean debug = log.isDebugEnabled();
            final StopWatch watch = new StopWatch();
            try {
                for (X509Certificate cert : chain) {
                    String[] cnValues = AbstractVerifier.getCNs(cert);
                    String alias;

                    if (cnValues != null && cnValues.length > 0) {
                        alias = cnValues[0];
                    } else {
                        alias = "UnknownCN";
                    }

                    alias += "-ts=" + System.currentTimeMillis();

                    trustStore.setCertificateEntry(alias, cert);
                }
                KEYSTORE_WRITER_LOCK.lockInterruptibly();
                hasLock = true;
                keyStoreFileOutputStream = new FileOutputStream(keystoreConfig.getFilePath());
                trustStore.store(keyStoreFileOutputStream, keystoreConfig.getFilePassword().toCharArray());
            } catch (FileNotFoundException e) {
                // Can't find the keystore in the path
                log.error("Can't find the keystore in " + keystoreConfig.getFilePath() + ". Error message:"
                        + e.getMessage(), e);
            } catch (NoSuchAlgorithmException e) {
                log.error("The algorithm is not supported. Error message:" + e.getMessage(), e);
            } catch (Exception e) {
                // expect KeyStoreException, IOException
                log.error("Exception when trying to import certificate: " + e.getMessage(), e);
            } finally {
                close(keyStoreFileOutputStream);
                keyStoreFileOutputStream = null;
                if (hasLock) {
                    KEYSTORE_WRITER_LOCK.unlock();
                }
                if (debug)
                    log.debug("importCert: " + watch);
            }
        }

        private void close(FileOutputStream keyStoreFileOutputStream) {
            if (keyStoreFileOutputStream != null) {
                try {
                    keyStoreFileOutputStream.close();
                } catch (IOException e) {
                    log.error(e, e);
                }
            }
        }
    };
}