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.codice.ddf.security.validator.pki.TestPKITokenValidator.java

@Before
public void setup() {
    pkiTokenValidator = new PKITokenValidator();
    pkiTokenValidator.setSignaturePropertiesPath(
            TestPKITokenValidator.class.getResource("/signature.properties").getPath());
    pkiTokenValidator.setRealms(Arrays.asList("karaf"));
    pkiTokenValidator.init();/* w w w. ja v a  2  s  .  c  o m*/

    try {
        KeyStore trustStore = KeyStore.getInstance(System.getProperty("javax.net.ssl.keyStoreType"));
        InputStream trustFIS = TestPKITokenValidator.class.getResourceAsStream("/serverKeystore.jks");
        try {
            trustStore.load(trustFIS, "changeit".toCharArray());
        } catch (CertificateException e) {
            fail(e.getMessage());
        } finally {
            IOUtils.closeQuietly(trustFIS);
        }
        Certificate[] certs = trustStore.getCertificateChain("localhost");
        certificates = new X509Certificate[certs.length];
        for (int i = 0; i < certs.length; i++) {
            certificates[i] = (X509Certificate) certs[i];
        }

        trustStore = KeyStore.getInstance(System.getProperty(SecurityConstants.KEYSTORE_TYPE));
        trustFIS = TestPKITokenValidator.class.getResourceAsStream("/badKeystore.jks");
        try {
            trustStore.load(trustFIS, "changeit".toCharArray());
        } catch (CertificateException e) {
            fail(e.getMessage());
        } finally {
            IOUtils.closeQuietly(trustFIS);
        }
        certs = trustStore.getCertificateChain("badhost");
        badCertificates = new X509Certificate[certs.length];
        for (int i = 0; i < certs.length; i++) {
            badCertificates[i] = (X509Certificate) certs[i];
        }
        merlin = new Merlin(
                PropertiesLoader.loadProperties(
                        TestPKITokenValidator.class.getResource("/signature.properties").getPath()),
                PKITokenValidator.class.getClassLoader(), null);
    } catch (Exception e) {
        fail(e.getMessage());
    }
}

From source file:org.opendaylight.aaa.cert.impl.ODLKeyTool.java

private X509Certificate getCertificate(String certificate) {
    if (certificate.isEmpty()) {
        return null;
    }//from w w w .  j  a  va 2 s  .co  m

    if (certificate.contains(KeyStoreConstant.BEGIN_CERTIFICATE)) {
        final int fIdx = certificate.indexOf(KeyStoreConstant.BEGIN_CERTIFICATE)
                + KeyStoreConstant.BEGIN_CERTIFICATE.length();
        final int sIdx = certificate.indexOf(KeyStoreConstant.END_CERTIFICATE);
        certificate = certificate.substring(fIdx, sIdx);
    }
    final byte[] byteCert = Base64.decodeBase64(certificate);
    final InputStream inputStreamCert = new ByteArrayInputStream(byteCert);
    CertificateFactory certFactory;
    try {
        certFactory = CertificateFactory.getInstance("X.509");
        final X509Certificate newCert = (X509Certificate) certFactory.generateCertificate(inputStreamCert);
        newCert.checkValidity();
        return newCert;
    } catch (final CertificateException e) {
        LOG.error("Failed to get certificate {}", e.getMessage());
        return null;
    }
}

From source file:com.netscape.cmstools.client.ClientCertValidateCLI.java

public boolean verifySystemCertByNickname(String nickname, String certusage) throws Exception {
    CertificateUsage cu = getCertificateUsage(certusage);
    int ccu = 0;//from   w  w w .  ja v  a2 s . c om

    if (cu == null) {
        throw new Exception("Unsupported certificate usage " + certusage + " in certificate " + nickname);
    }

    CryptoManager cm = CryptoManager.getInstance();
    if (cu.getUsage() != CertificateUsage.CheckAllUsages.getUsage()) {
        try {
            cm.verifyCertificate(nickname, true, cu);
            System.out.println("Valid certificate: " + nickname);
            return true;
        } catch (CertificateException e) {
            // Invalid certificate: (<code>) <message>
            System.out.println(e.getMessage());
            return false;
        }

    } else {
        // check all possible usages
        ccu = cm.isCertValid(nickname, true);
        if (ccu == CertificateUsage.basicCertificateUsages) {
            /* cert is good for nothing */
            System.out.println("Cert is good for nothing: " + nickname);
            return false;
        } else {
            List<String> usages = new ArrayList<String>();
            if ((ccu & CertificateUsage.SSLServer.getUsage()) != 0)
                usages.add("SSLServer");
            if ((ccu & CertificateUsage.SSLClient.getUsage()) != 0)
                usages.add("SSLClient");
            if ((ccu & CertificateUsage.SSLServerWithStepUp.getUsage()) != 0)
                usages.add("SSLServerWithStepUp");
            if ((ccu & CertificateUsage.SSLCA.getUsage()) != 0)
                usages.add("SSLCA");
            if ((ccu & CertificateUsage.EmailSigner.getUsage()) != 0)
                usages.add("EmailSigner");
            if ((ccu & CertificateUsage.EmailRecipient.getUsage()) != 0)
                usages.add("EmailRecipient");
            if ((ccu & CertificateUsage.ObjectSigner.getUsage()) != 0)
                usages.add("ObjectSigner");
            if ((ccu & CertificateUsage.UserCertImport.getUsage()) != 0)
                usages.add("UserCertImport");
            if ((ccu & CertificateUsage.VerifyCA.getUsage()) != 0)
                usages.add("VerifyCA");
            if ((ccu & CertificateUsage.ProtectedObjectSigner.getUsage()) != 0)
                usages.add("ProtectedObjectSigner");
            if ((ccu & CertificateUsage.StatusResponder.getUsage()) != 0)
                usages.add("StatusResponder");
            if ((ccu & CertificateUsage.AnyCA.getUsage()) != 0)
                usages.add("AnyCA");
            System.out.println("Cert has the following usages: " + StringUtils.join(usages, ','));
            return true;
        }
    }
}

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

/**
 * @param cert/*from w ww  .ja va2s.c o m*/
 * @return true when the certificate is self signed
 */
public static boolean isCertificateSelfSigned(X509Certificate cert) {
    try {
        PublicKey publicKey = cert.getPublicKey();
        cert.verify(publicKey);
        return true;
    } catch (java.security.SignatureException sigEx) {
        LOG.info("ERROR : SignatureException {}", sigEx.getMessage());
        LOG.debug("ERROR : SignatureException {}", sigEx);
        return false;
    } catch (InvalidKeyException keyEx) {
        // Invalid key --> not self-signed
        LOG.info("ERROR : InvalidKeyException {}", keyEx.getMessage());
        LOG.debug("ERROR : InvalidKeyException {}", keyEx);
        return false;
    } catch (CertificateException certExc) {
        LOG.info("ERROR : CertificateException {}", certExc.getMessage());
        LOG.debug("ERROR : CertificateException {}", certExc);
        return false;
    } catch (NoSuchAlgorithmException nsaExc) {
        LOG.info("ERROR : Bad algorithm: " + nsaExc.getMessage());
        LOG.debug("ERROR : Bad algorithm: " + nsaExc);
        return false;
    } catch (NoSuchProviderException nspExc) {
        LOG.info("ERROR : Bad provider: " + nspExc.getMessage());
        LOG.debug("ERROR : Bad provider: " + nspExc);
        return false;
    }
}

From source file:org.gluu.oxeleven.rest.GenerateKeyRestServiceImpl.java

public Response generateKey(String sigAlg, Long expirationTime) {
    Response.ResponseBuilder builder = Response.ok();

    try {//from   w  ww . ja  va  2s  . c o  m
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromName(sigAlg);

        if (signatureAlgorithm == null) {
            builder = Response.status(Response.Status.BAD_REQUEST);
            builder.entity(StringUtils.getErrorResponse("invalid_request",
                    "The request asked for an operation that cannot be supported because the server does not support the provided signatureAlgorithm parameter."));
        } else if (expirationTime == null) {
            builder = Response.status(Response.Status.BAD_REQUEST);
            builder.entity(StringUtils.getErrorResponse("invalid_request",
                    "The request asked for an operation that cannot be supported because the expiration time parameter is mandatory."));
        } else if (signatureAlgorithm == SignatureAlgorithm.NONE
                || signatureAlgorithm.getFamily().equals(SignatureAlgorithmFamily.HMAC)) {
            builder = Response.status(Response.Status.BAD_REQUEST);
            builder.entity(StringUtils.getErrorResponse("invalid_request",
                    "The provided signature algorithm parameter is not supported."));
        } else {
            String dnName = configuration.getDnName();
            String alias = pkcs11Service.generateKey(dnName, signatureAlgorithm, expirationTime);
            PublicKey publicKey = pkcs11Service.getPublicKey(alias);
            Certificate certificate = pkcs11Service.getCertificate(alias);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put(KEY_ID, alias);
            jsonObject.put(KEY_TYPE, signatureAlgorithm.getFamily());
            jsonObject.put(KEY_USE, "sig");
            jsonObject.put(ALGORITHM, signatureAlgorithm.getName());
            jsonObject.put(EXPIRATION_TIME, expirationTime);
            if (SignatureAlgorithmFamily.RSA.equals(signatureAlgorithm.getFamily())) {
                RSAPublicKeyImpl rsaPublicKey = (RSAPublicKeyImpl) publicKey;
                jsonObject.put(MODULUS, Base64Util.base64UrlEncode(rsaPublicKey.getModulus().toByteArray()));
                jsonObject.put(EXPONENT,
                        Base64Util.base64UrlEncode(rsaPublicKey.getPublicExponent().toByteArray()));
            } else if (SignatureAlgorithmFamily.EC.equals(signatureAlgorithm.getFamily())) {
                ECPublicKey ecPublicKey = (ECPublicKey) publicKey;
                jsonObject.put(CURVE, signatureAlgorithm.getCurve());
                jsonObject.put(X, Base64Util.base64UrlEncode(ecPublicKey.getW().getAffineX().toByteArray()));
                jsonObject.put(Y, Base64Util.base64UrlEncode(ecPublicKey.getW().getAffineY().toByteArray()));
            }
            JSONArray x5c = new JSONArray();
            x5c.put(Base64.encodeBase64String(certificate.getEncoded()));
            jsonObject.put(CERTIFICATE_CHAIN, x5c);

            builder.entity(jsonObject.toString());
        }
    } catch (CertificateException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (KeyStoreException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (InvalidKeyException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (InvalidAlgorithmParameterException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (NoSuchProviderException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (SignatureException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (JSONException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (Exception e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    }

    CacheControl cacheControl = new CacheControl();
    cacheControl.setNoTransform(false);
    cacheControl.setNoStore(true);
    builder.cacheControl(cacheControl);
    builder.header("Pragma", "no-cache");
    return builder.build();
}

From source file:be.e_contract.eid.applet.service.impl.handler.IdentityDataMessageHandler.java

/**
 * Tries to parse the X509 certificate./*  w w w.  j ava2  s . c  om*/
 * 
 * @param certFile
 * @return the X509 certificate, or <code>null</code> in case of a DER
 *         decoding error.
 */
private X509Certificate getCertificate(byte[] certFile) {
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
        X509Certificate certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(certFile));
        return certificate;
    } catch (CertificateException e) {
        LOG.warn("certificate error: " + e.getMessage(), e);
        LOG.debug("certificate size: " + certFile.length);
        LOG.debug("certificate file content: " + Hex.encodeHexString(certFile));
        /*
         * Missing eID authentication and eID non-repudiation certificates
         * could become possible for future eID cards. A missing certificate
         * is represented as a block of 1300 null bytes.
         */
        if (1300 == certFile.length) {
            boolean missingCertificate = true;
            for (int idx = 0; idx < certFile.length; idx++) {
                if (0 != certFile[idx]) {
                    missingCertificate = false;
                }
            }
            if (missingCertificate) {
                LOG.debug("the certificate data indicates a missing certificate");
            }
        }
        return null;
    }
}

From source file:org.codice.ddf.security.validator.pki.PKITokenValidatorTest.java

@Before
public void setup() {
    pkiTokenValidator = new PKITokenValidator();
    pkiTokenValidator.setSignaturePropertiesPath(
            PKITokenValidatorTest.class.getResource("/signature.properties").getPath());
    pkiTokenValidator.setRealms(Arrays.asList("karaf"));
    pkiTokenValidator.init();/*  www . j  a  v a  2  s.  co m*/

    try {
        KeyStore trustStore = KeyStore.getInstance(System.getProperty("javax.net.ssl.keyStoreType"));
        InputStream trustFIS = PKITokenValidatorTest.class.getResourceAsStream("/serverKeystore.jks");
        try {
            trustStore.load(trustFIS, "changeit".toCharArray());
        } catch (CertificateException e) {
            fail(e.getMessage());
        } finally {
            IOUtils.closeQuietly(trustFIS);
        }
        Certificate[] certs = trustStore.getCertificateChain("localhost");
        certificates = new X509Certificate[certs.length];
        for (int i = 0; i < certs.length; i++) {
            certificates[i] = (X509Certificate) certs[i];
        }

        trustStore = KeyStore.getInstance(System.getProperty(SecurityConstants.KEYSTORE_TYPE));
        trustFIS = PKITokenValidatorTest.class.getResourceAsStream("/badKeystore.jks");
        try {
            trustStore.load(trustFIS, "changeit".toCharArray());
        } catch (CertificateException e) {
            fail(e.getMessage());
        } finally {
            IOUtils.closeQuietly(trustFIS);
        }
        certs = trustStore.getCertificateChain("badhost");
        badCertificates = new X509Certificate[certs.length];
        for (int i = 0; i < certs.length; i++) {
            badCertificates[i] = (X509Certificate) certs[i];
        }
        merlin = new Merlin(
                PropertiesLoader.loadProperties(
                        PKITokenValidatorTest.class.getResource("/signature.properties").getPath()),
                PKITokenValidator.class.getClassLoader(), null);

        KeyStore keystore = KeyStore.getInstance(System.getProperty(SecurityConstants.KEYSTORE_TYPE));
        try (InputStream keystoreIS = PKITokenValidatorTest.class.getResourceAsStream("/test-user.jks")) {
            keystore.load(keystoreIS, "changeit".toCharArray());
        }
        Certificate cert = keystore.getCertificate("test");
        userCertificates = new X509Certificate[] { (X509Certificate) cert };

    } catch (Exception e) {
        fail(e.getMessage());
    }
}

From source file:be.fedict.hsm.client.HSMProxyClient.java

/**
 * Main constructor. To access the HSM Proxy web service, you need to have a
 * valid credential.//from  w ww  .  j  a  v a2  s.c  om
 * 
 * @param endpointAddress
 *            the HSM Proxy web service endpoint address.
 * @param credentialPrivateKey
 *            the credential private key.
 * @param credentialCertificate
 *            the corresponding credential X509 certificate.
 */
public HSMProxyClient(String endpointAddress, PrivateKey credentialPrivateKey,
        X509Certificate credentialCertificate) {
    this.endpointAddress = endpointAddress;

    DigitalSignatureService digitalSignatureService = DigitalSignatureServiceFactory.getInstance();
    this.dssPort = digitalSignatureService.getDigitalSignatureServicePort();

    BindingProvider bindingProvider = (BindingProvider) this.dssPort;
    bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointAddress);

    this.dssObjectFactory = new ObjectFactory();
    this.dsObjectFactory = new be.fedict.hsm.ws.jaxb.xmldsig.ObjectFactory();
    this.hsmObjectFactory = new be.fedict.hsm.ws.jaxb.hsm.ObjectFactory();

    try {
        this.certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException("X509 certificate factory error: " + e.getMessage(), e);
    }

    Binding binding = bindingProvider.getBinding();
    List<Handler> handlerChain = binding.getHandlerChain();
    handlerChain.add(new WSSecuritySOAPHandler(credentialPrivateKey, credentialCertificate));
    binding.setHandlerChain(handlerChain);
}

From source file:be.fedict.eid.dss.protocol.simple.client.SignatureResponseProcessor.java

/**
 * Main constructor./*from  ww  w  .ja v  a  2 s .  com*/
 * 
 * @param serviceFingerprint
 *            the service X509 certificate fingerprint (SHA1) used to
 *            validate the signatory of the service signature.
 */
public SignatureResponseProcessor(byte[] serviceFingerprint) {
    try {
        this.certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException("could not create certificate factory instance: " + e.getMessage(), e);
    }
    this.serviceFingerprint = serviceFingerprint;
}

From source file:be.fedict.commons.eid.consumer.BeIDIntegrity.java

/**
 * Loads a DER-encoded X509 certificate from a byte array.
 * /*  w  ww .  j a  va2s .  c om*/
 * @param encodedCertificate
 * @return
 */
public X509Certificate loadCertificate(final byte[] encodedCertificate) {
    X509Certificate certificate;
    try {
        certificate = (X509Certificate) this.certificateFactory
                .generateCertificate(new ByteArrayInputStream(encodedCertificate));
    } catch (final CertificateException cex) {
        throw new RuntimeException("X509 decoding error: " + cex.getMessage(), cex);
    }
    return certificate;
}