Example usage for java.security.cert CertificateException CertificateException

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

Introduction

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

Prototype

public CertificateException(Throwable cause) 

Source Link

Document

Creates a CertificateException with the specified cause and a detail message of (cause==null ?

Usage

From source file:org.apache.hadoop.security.ssl.ReloadingX509TrustManager.java

@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    X509TrustManager tm = trustManagerRef.get();
    if (tm != null) {
        tm.checkClientTrusted(chain, authType);
    } else {//  w ww  .j a v  a 2  s  .  c  o  m
        throw new CertificateException("Unknown client chain certificate: " + chain[0].toString());
    }
}

From source file:androidGLUESigner.pdf.PDFSignerEngine.java

/**
 * get the certificate chain/*w  w w .  ja  v  a 2 s .  c om*/
 * @return the certificate chain
 */
private Certificate[] getCertificateChain() throws CertificateException {
    if (certificateChain == null) {
        if (cert == null || issuerCert == null)
            throw new CertificateException("Certificates missing");

        certificateChain = new Certificate[2];
        certificateChain[0] = cert;
        certificateChain[1] = issuerCert;
    }

    return certificateChain;
}

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static void verify(String cert64, String public64) throws CertificateException, NoSuchAlgorithmException,
        InvalidKeySpecException, SignatureException, NoSuchProviderException, InvalidKeyException {
    if (StringUtils.isBlank(cert64)) {
        throw new CertificateException("Certificate is empty");
    } else if (StringUtils.isBlank(public64)) {
        throw new InvalidKeyException("Public key is empty");
    }//from  ww w  . j a  v  a  2  s. c o m
    byte[] cert = Base64.decode(cert64);
    byte[] key = Base64.decode(public64);
    X509CertImpl x509 = new X509CertImpl(cert);

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(key);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

    x509.verify(publicKey);
    x509.checkValidity(utc.getTime());
}

From source file:net.shirayu.android.WlanLogin.MyHttpClient.java

public static X509Certificate readPem(InputStream stream)
        throws CertificateException, NoSuchProviderException, IOException {
    CertPath cp;/*from  w  w  w  . j av  a  2s  .  c o m*/
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
        cp = cf.generateCertPath(stream, "PEM");
    } finally {
        stream.close();
    }
    List<? extends Certificate> certs = cp.getCertificates();
    if (certs.size() < 1) {
        throw new CertificateException("Certificate list is empty");
    } else if (certs.size() > 1) {
        throw new CertificateException("Intermediate certificate is not allowed");
    }
    if (certs.get(0) instanceof X509Certificate) {
        X509Certificate cert = (X509Certificate) certs.get(0);
        cert.checkValidity();
        return cert;
    } else {
        throw new CertificateException("Certificate is not X509Certificate");
    }
}

From source file:org.apache.hadoop.security.ssl.ReloadingX509TrustManager.java

@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    X509TrustManager tm = trustManagerRef.get();
    if (tm != null) {
        tm.checkServerTrusted(chain, authType);
    } else {// w  w w  .ja v a 2s.co m
        throw new CertificateException("Unknown server chain certificate: " + chain[0].toString());
    }
}

From source file:com.otterca.persistence.dao.X509CertificateDaoDatastore.java

/**
 * Verify that cached results are consistent. It's a strong indication that
 * someone has been screwing with the database if the values are
 * inconsistent. This is computationally expensive but the cost of a
 * corrupted database is far worse.//from w ww  .  j a  v a2  s .  c o m
 * 
 * @param entity
 * @param cert
 */
public void validate(Entity entity, X509Certificate cert) throws CertificateException {
    if (!cert.getSerialNumber().equals(entity.getProperty(SERIAL_NUMBER))) {
        throw new CertificateException("serial number did not match");
    }
    if (!cert.getIssuerDN().equals(entity.getProperty(ISSUER_DN))) {
        throw new CertificateException("issuer dn did not match");
    }
    if (!cert.getSubjectDN().equals(entity.getProperty(SUBJECT_DN))) {
        throw new CertificateException("subject dn did not match");
    }
    if (!cert.getNotBefore().equals(entity.getProperty(NOT_BEFORE))) {
        throw new CertificateException("notBefore did not match");
    }
    if (!cert.getNotAfter().equals(entity.getProperty(NOT_AFTER))) {
        throw new CertificateException("notAfter did not match");
    }
    if (!x509CertUtil.getName(cert).equals(entity.getProperty(COMMON_NAME))) {
        throw new CertificateException("common name did not match");
    }
    if (!x509CertUtil.getFingerprint(cert).equals(entity.getProperty(FINGERPRINT))) {
        throw new CertificateException("cached fingerprints did not match");
    }
    if (!x509CertUtil.getCertificateHash(cert).equals(entity.getProperty(CERT_HASH))) {
        throw new CertificateException("cached certificate hash did not match");
    }
    if (!x509CertUtil.getIHash(cert).equals(entity.getProperty(ISSUER_HASH))) {
        throw new CertificateException("cached issuer hash did not match");
    }
    if (!x509CertUtil.getSHash(cert).equals(entity.getProperty(SUBJECT_HASH))) {
        throw new CertificateException("cached subject hash did not match");
    }
    if (!x509CertUtil.getAkidHash(cert).equals(entity.getProperty(AKID_HASH))) {
        throw new CertificateException("cached AKID hash did not match");
    }
    if (!x509CertUtil.getSkidHash(cert).equals(entity.getProperty(SKID_HASH))) {
        throw new CertificateException("cached SKID hash did not match");
    }
}

From source file:org.cesecore.keys.util.KeyStoreTools.java

private X509Certificate getSelfCertificate(String myname, long validity, String sigAlg, KeyPair keyPair)
        throws InvalidKeyException, CertificateException {
    final long currentTime = new Date().getTime();
    final Date firstDate = new Date(currentTime - 24 * 60 * 60 * 1000);
    final Date lastDate = new Date(currentTime + validity * 1000);
    final X500Name issuer = new X500Name(myname);
    final BigInteger serno = BigInteger.valueOf(firstDate.getTime());
    final PublicKey publicKey = keyPair.getPublic();
    if (publicKey == null) {
        throw new InvalidKeyException("Public key is null");
    }/*from w  w w .  j  av a 2s .  c  om*/

    try {
        final X509v3CertificateBuilder cg = new JcaX509v3CertificateBuilder(issuer, serno, firstDate, lastDate,
                issuer, publicKey);
        log.debug("Keystore signing algorithm " + sigAlg);
        final ContentSigner signer = new BufferingContentSigner(
                new JcaContentSignerBuilder(sigAlg).setProvider(this.providerName).build(keyPair.getPrivate()),
                20480);
        final X509CertificateHolder cert = cg.build(signer);
        return (X509Certificate) CertTools.getCertfromByteArray(cert.getEncoded());
    } catch (OperatorCreationException e) {
        log.error("Error creating content signer: ", e);
        throw new CertificateException(e);
    } catch (IOException e) {
        throw new CertificateException("Could not read certificate", e);
    }
}

From source file:org.globus.security.stores.PEMKeyStore.java

/**
 * Persist the security material in this keystore. If the object has a path
 * associated with it, the object will be persisted to that path. Otherwise
 * it will be stored in the default certificate directory. As a result, the
 * parameters of this method are ignored.
 * /*from   www. ja v  a 2s  .c  o  m*/
 * @param outputStream
 *            This parameter is ignored.
 * @param chars
 *            This parameter is ignored.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 */
@Override
public void engineStore(OutputStream outputStream, char[] chars)
        throws IOException, NoSuchAlgorithmException, CertificateException {
    for (SecurityObjectWrapper<?> object : this.aliasObjectMap.values()) {
        if (object instanceof Storable) {
            try {
                ((Storable) object).store();
            } catch (ResourceStoreException e) {
                throw new CertificateException(e);
            }
        }
    }
}

From source file:be.fedict.trust.client.XKMS2Client.java

/**
 * If set, unilateral TLS authentication will occurs, verifying the server
 * {@link X509Certificate} specified {@link PublicKey}.
 * <p/>/*from  w w w .  ja v  a  2  s  . c o m*/
 * WARNING: only works when using the JAX-WS RI.
 * 
 * @param publicKey
 *            public key to validate server TLS certificate against.
 */
public void setServicePublicKey(final PublicKey publicKey) {
    // Create TrustManager
    TrustManager[] trustManager = { new X509TrustManager() {

        public X509Certificate[] getAcceptedIssuers() {

            return null;
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            X509Certificate serverCertificate = chain[0];
            LOG.debug("server X509 subject: " + serverCertificate.getSubjectX500Principal().toString());
            LOG.debug("authentication type: " + authType);
            if (null == publicKey) {
                LOG.warn("not performing any server certificate validation at all");
                return;
            }

            try {
                serverCertificate.verify(publicKey);
                LOG.debug("valid server certificate");
            } catch (InvalidKeyException e) {
                throw new CertificateException("Invalid Key");
            } catch (NoSuchAlgorithmException e) {
                throw new CertificateException("No such algorithm");
            } catch (NoSuchProviderException e) {
                throw new CertificateException("No such provider");
            } catch (SignatureException e) {
                throw new CertificateException("Wrong signature");
            }
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            throw new CertificateException("this trust manager cannot be used as server-side trust manager");
        }
    } };

    // Create SSL Context
    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        SecureRandom secureRandom = new SecureRandom();
        sslContext.init(null, trustManager, secureRandom);
        LOG.debug("SSL context provider: " + sslContext.getProvider().getName());

        // Setup TrustManager for validation
        Map<String, Object> requestContext = ((BindingProvider) this.port).getRequestContext();
        requestContext.put("com.sun.xml.ws.transport.https.client.SSLSocketFactory",
                sslContext.getSocketFactory());

    } catch (KeyManagementException e) {
        String msg = "key management error: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    } catch (NoSuchAlgorithmException e) {
        String msg = "TLS algo not present: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    }
}

From source file:com.amazon.speech.speechlet.authentication.SpeechletRequestSignatureVerifier.java

/**
 * Verifies the signing certificate chain URL and returns a {@code URL} object.
 *
 * @param signingCertificateChainUrl//from w  w w  .  j  a va2  s  . co m
 *            the external form of the URL
 * @return the URL
 * @throws CertificateException
 *             if the URL is malformed or contains an invalid hostname, an unsupported protocol,
 *             or an invalid port (if specified)
 */
static URL getAndVerifySigningCertificateChainUrl(final String signingCertificateChainUrl)
        throws CertificateException {
    try {
        URL url = new URI(signingCertificateChainUrl).normalize().toURL();
        // Validate the hostname
        if (!VALID_SIGNING_CERT_CHAIN_URL_HOST_NAME.equalsIgnoreCase(url.getHost())) {
            throw new CertificateException(String.format(
                    "SigningCertificateChainUrl [%s] does not contain the required hostname" + " of [%s]",
                    signingCertificateChainUrl, VALID_SIGNING_CERT_CHAIN_URL_HOST_NAME));
        }

        // Validate the path prefix
        String path = url.getPath();
        if (!path.startsWith(VALID_SIGNING_CERT_CHAING_URL_PATH_PREFIX)) {
            throw new CertificateException(String.format(
                    "SigningCertificateChainUrl path [%s] is invalid. Expecting path to " + "start with [%s]",
                    signingCertificateChainUrl, VALID_SIGNING_CERT_CHAING_URL_PATH_PREFIX));
        }

        // Validate the protocol
        String urlProtocol = url.getProtocol();
        if (!VALID_SIGNING_CERT_CHAIN_PROTOCOL.equalsIgnoreCase(urlProtocol)) {
            throw new CertificateException(
                    String.format("SigningCertificateChainUrl [%s] contains an unsupported protocol [%s]",
                            signingCertificateChainUrl, urlProtocol));
        }

        // Validate the port uses the default of 443 for HTTPS if explicitly defined in the URL
        int urlPort = url.getPort();
        if ((urlPort != UNSPECIFIED_SIGNING_CERT_CHAIN_URL_PORT_VALUE) && (urlPort != url.getDefaultPort())) {
            throw new CertificateException(
                    String.format("SigningCertificateChainUrl [%s] contains an invalid port [%d]",
                            signingCertificateChainUrl, urlPort));
        }

        return url;
    } catch (IllegalArgumentException | MalformedURLException | URISyntaxException ex) {
        throw new CertificateException(
                String.format("SigningCertificateChainUrl [%s] is malformed", signingCertificateChainUrl), ex);
    }
}