javax.security.cert.CertificateException Java Examples

The following examples show how to use javax.security.cert.CertificateException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SSLHeaderHandler.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    final String sessionId = exchange.getRequestHeader(SSL_SESSION_ID);
    final String cipher = exchange.getRequestHeader(SSL_CIPHER);
    String clientCert = exchange.getRequestHeader(SSL_CLIENT_CERT);
    //the proxy client replaces \n with ' '
    if (clientCert != null && clientCert.length() > 28) {
        StringBuilder sb = new StringBuilder(clientCert.length() + 1);
        sb.append(Certificates.BEGIN_CERT);
        sb.append('\n');
        sb.append(clientCert.replace(' ', '\n').substring(28, clientCert.length() - 26));//core certificate data
        sb.append('\n');
        sb.append(Certificates.END_CERT);
        clientCert = sb.toString();
    }
    if (clientCert != null || sessionId != null || cipher != null) {
        try {
            SSLSessionInfo info = new BasicSSLSessionInfo(sessionId, cipher, clientCert);
            exchange.setRequestScheme(HTTPS);
            exchange.setSslSessionInfo(info);
        } catch (java.security.cert.CertificateException | CertificateException e) {
            UndertowLogger.REQUEST_LOGGER.debugf(e, "Could not create certificate from header %s", clientCert);
        }
    }
    next.handleRequest(exchange);
}
 
Example #2
Source File: BasicMutualAuthTest.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * Scenario:
 *   - Select invalid key alias (no such key).
 *   - Negotiation will fail
 * @throws CertificateException the certificate exception
 * @throws IOException the IO exception
 */
@Test
public void shouldFailWithInValidKeyAlias() throws CertificateException, IOException  {
    config.put(TLSOptions.TLS_TRUSTSTORE, getResourcePath("2waytest/basic_mutual_auth_2/gateway_ts.jks"));
    config.put(TLSOptions.TLS_TRUSTSTOREPASSWORD, "password");
    config.put(TLSOptions.TLS_KEYSTORE, getResourcePath("2waytest/basic_mutual_auth_2/gateway_ks.jks"));
    config.put(TLSOptions.TLS_KEYSTOREPASSWORD, "password");
    config.put(TLSOptions.TLS_KEYPASSWORD, "password");
    config.put(TLSOptions.TLS_ALLOWANYHOST, "true");
    config.put(TLSOptions.TLS_ALLOWSELFSIGNED, "false");
    // No such key exists in the keystore
    config.put(TLSOptions.TLS_KEYALIASES, "xxx");

    HttpConnectorFactory factory = new HttpConnectorFactory(config);
    IApiConnector connector = factory.createConnector(request, api, RequiredAuthType.MTLS, false, new ConnectorConfigImpl());
    IApiConnection connection = connector.connect(request,
            new IAsyncResultHandler<IApiConnectionResponse>() {

                @Override
                public void handle(IAsyncResult<IApiConnectionResponse> result) {
                    Assert.assertTrue(result.isError());
                }
            });

            connection.end();
}
 
Example #3
Source File: OpenSslEngine.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Override
public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException {
    // these are lazy created to reduce memory overhead
    X509Certificate[] c = x509PeerCerts;
    if (c == null) {
        if (SSL.isInInit(ssl) != 0) {
            throw new SSLPeerUnverifiedException("peer not verified");
        }
        byte[][] chain = SSL.getPeerCertChain(ssl);
        if (chain == null) {
            throw new SSLPeerUnverifiedException("peer not verified");
        }
        X509Certificate[] peerCerts = new X509Certificate[chain.length];
        for (int i = 0; i < peerCerts.length; i++) {
            try {
                peerCerts[i] = X509Certificate.getInstance(chain[i]);
            } catch (CertificateException e) {
                throw new IllegalStateException(e);
            }
        }
        c = x509PeerCerts = peerCerts;
    }
    return c;
}
 
Example #4
Source File: CertificateUtils.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
/**
 * Used to get the certificate alias for a certificate which is get from the Request .
 */
public static String getAliasFromRequest(String certB64) {
    try {
        byte[] decoded = java.util.Base64.getDecoder().decode(certB64);
        java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) CertificateFactory
                .getInstance("X.509").generateCertificate(new ByteArrayInputStream(decoded));
        String certificateAlias = LoadKeyStore.trustStore.getCertificateAlias(cert);
        if (certificateAlias != null) {
            return certificateAlias;
        }
        return "";
    } catch (java.security.cert.CertificateException | KeyStoreException e) {
        String msg = "Error while decoding certificate present in the context and validating with the trust store.";
        log.error(msg, e);
        throw ErrorUtils.getBallerinaError(msg, e);
    }
}
 
Example #5
Source File: CertificateUtils.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
public static String getAliasFromHeaderCert(String base64EncodedCertificate) {
    try {
        base64EncodedCertificate = URLDecoder.decode(base64EncodedCertificate).
                replaceAll(Constants.BEGIN_CERTIFICATE_STRING, "").replaceAll(Constants.END_CERTIFICATE_STRING, "");
        byte[] bytes = Base64.decodeBase64(base64EncodedCertificate);
        InputStream inputStream = new ByteArrayInputStream(bytes);
        X509Certificate x509Certificate = X509Certificate.getInstance(inputStream);
        if (getAliasFromTrustStore(x509Certificate, LoadKeyStore.trustStore) != null) {
            return getAliasFromTrustStore(x509Certificate, LoadKeyStore.trustStore);
        }
        return "";
    } catch (KeyStoreException | java.security.cert.CertificateException | CertificateException e) {
        String msg = "Error while decoding certificate present in the header and validating with the trust store.";
        log.error(msg, e);
        throw ErrorUtils.getBallerinaError(msg, e);
    }
}
 
Example #6
Source File: CertificateUtils.java    From product-microgateway with Apache License 2.0 5 votes vote down vote up
/**
 *  Used to get the certificate alias for a certificate which is get from header send by payload.
 */
public static String getAliasFromTrustStore(X509Certificate certificate, KeyStore truststore) throws
        java.security.cert.CertificateException, CertificateEncodingException, KeyStoreException {
    KeyStore trustStore = truststore;
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    byte[] certificateEncoded = certificate.getEncoded();
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(certificateEncoded);
    java.security.cert.X509Certificate x509Certificate =
            (java.security.cert.X509Certificate) cf.generateCertificate(byteArrayInputStream);
    x509Certificate.checkValidity();
    String certificateAlias = trustStore.getCertificateAlias(x509Certificate);
    return certificateAlias;
}
 
Example #7
Source File: BasicMutualAuthTest.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * Scenario:
 *   - First alias invalid, second valid.
 *   - Mutual trust exists between gateway and API.
 *   - We must fall back to the valid alias.
 * @throws CertificateException the certificate exception
 * @throws IOException the IO exception
 */
@Test
public void shouldFallbackWhenMultipleAliasesAvailable() throws CertificateException, IOException  {
    config.put(TLSOptions.TLS_TRUSTSTORE, getResourcePath("2waytest/basic_mutual_auth_2/gateway_ts.jks"));
    config.put(TLSOptions.TLS_TRUSTSTOREPASSWORD, "password");
    config.put(TLSOptions.TLS_KEYSTORE, getResourcePath("2waytest/basic_mutual_auth_2/gateway_ks.jks"));
    config.put(TLSOptions.TLS_KEYSTOREPASSWORD, "password");
    config.put(TLSOptions.TLS_KEYPASSWORD, "password");
    config.put(TLSOptions.TLS_ALLOWANYHOST, "true");
    config.put(TLSOptions.TLS_ALLOWSELFSIGNED, "false");
    // Only gateway2 is valid. `unrelated` is real but not trusted by API. others don't exist.
    config.put(TLSOptions.TLS_KEYALIASES, "unrelated, owt, or, nowt, gateway2, sonorous, unrelated");

    InputStream inStream = new FileInputStream(getResourcePath("2waytest/basic_mutual_auth_2/gateway2.cer"));
    final X509Certificate expectedCert = X509Certificate.getInstance(inStream);
    inStream.close();

    HttpConnectorFactory factory = new HttpConnectorFactory(config);
    IApiConnector connector = factory.createConnector(request, api, RequiredAuthType.MTLS, false, new ConnectorConfigImpl());
    IApiConnection connection = connector.connect(request,
            new IAsyncResultHandler<IApiConnectionResponse>() {

                @Override
                public void handle(IAsyncResult<IApiConnectionResponse> result) {
                    if (result.isError())
                        throw new RuntimeException(result.getError());

                    Assert.assertTrue(result.isSuccess());
                    // Assert that the expected certificate (associated with the private key by virtue)
                    // was the one used.
                    Assert.assertEquals(expectedCert.getSerialNumber(), clientSerial);
                }
            });

    connection.end();
}
 
Example #8
Source File: BasicMutualAuthTest.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * Scenario:
 *   - Select client key alias `gateway2`.
 *   - Mutual trust exists between gateway and API
 *   - We must use the `gateway2` cert NOT `gateway`.
 * @throws CertificateException the certificate exception
 * @throws IOException the IO exception
 */
@Test
public void shouldSucceedWhenValidKeyAlias() throws CertificateException, IOException  {
    config.put(TLSOptions.TLS_TRUSTSTORE, getResourcePath("2waytest/basic_mutual_auth_2/gateway_ts.jks"));
    config.put(TLSOptions.TLS_TRUSTSTOREPASSWORD, "password");
    config.put(TLSOptions.TLS_KEYSTORE, getResourcePath("2waytest/basic_mutual_auth_2/gateway_ks.jks"));
    config.put(TLSOptions.TLS_KEYSTOREPASSWORD, "password");
    config.put(TLSOptions.TLS_KEYPASSWORD, "password");
    config.put(TLSOptions.TLS_ALLOWANYHOST, "true");
    config.put(TLSOptions.TLS_ALLOWSELFSIGNED, "false");

    config.put(TLSOptions.TLS_KEYALIASES, "gateway2");

    InputStream inStream = new FileInputStream(getResourcePath("2waytest/basic_mutual_auth_2/gateway2.cer"));
    final X509Certificate expectedCert = X509Certificate.getInstance(inStream);
    inStream.close();

    HttpConnectorFactory factory = new HttpConnectorFactory(config);
    IApiConnector connector = factory.createConnector(request, api, RequiredAuthType.MTLS, false, new ConnectorConfigImpl());
    IApiConnection connection = connector.connect(request,
            new IAsyncResultHandler<IApiConnectionResponse>() {

                @Override
                public void handle(IAsyncResult<IApiConnectionResponse> result) {
                    if (result.isError())
                        throw new RuntimeException(result.getError());

                    Assert.assertTrue(result.isSuccess());
                    // Assert that the expected certificate (associated with the private key by virtue)
                    // was the one used.
                    Assert.assertEquals(expectedCert.getSerialNumber(), clientSerial);
                }
            });

    connection.end();
}
 
Example #9
Source File: SSLHeaderHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    HeaderMap requestHeaders = exchange.getRequestHeaders();
    final String sessionId = requestHeaders.getFirst(SSL_SESSION_ID);
    final String cipher = requestHeaders.getFirst(SSL_CIPHER);
    String clientCert = requestHeaders.getFirst(SSL_CLIENT_CERT);
    //the proxy client replaces \n with ' '
    if (clientCert != null && clientCert.length() > 28) {
        StringBuilder sb = new StringBuilder(clientCert.length() + 1);
        sb.append(Certificates.BEGIN_CERT);
        sb.append('\n');
        sb.append(clientCert.replace(' ', '\n').substring(28, clientCert.length() - 26));//core certificate data
        sb.append('\n');
        sb.append(Certificates.END_CERT);
        clientCert = sb.toString();
    }
    if (clientCert != null || sessionId != null || cipher != null) {
        try {
            SSLSessionInfo info = new BasicSSLSessionInfo(sessionId, cipher, clientCert);
            exchange.setRequestScheme(HTTPS);
            exchange.getConnection().setSslSessionInfo(info);
            exchange.addExchangeCompleteListener(CLEAR_SSL_LISTENER);
        } catch (java.security.cert.CertificateException | CertificateException e) {
            UndertowLogger.REQUEST_LOGGER.debugf(e, "Could not create certificate from header %s", clientCert);
        }
    }
    next.handleRequest(exchange);
}
 
Example #10
Source File: CertInfo.java    From vertx-mqtt-broker with Apache License 2.0 5 votes vote down vote up
public CertInfo(String certPath) {
    try {
        FileInputStream file = new FileInputStream(certPath);
        X509Certificate cert = X509Certificate.getInstance(file);
        this.certs = new X509Certificate[]{cert};
    } catch(FileNotFoundException|CertificateException e) {
        logger.error(e.getMessage(), e);
    }
}
 
Example #11
Source File: mySSLSession.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public mySSLSession(Certificate[] xc) throws CertificateEncodingException, CertificateException {
    certs = xc;
    xCerts = new X509Certificate[xc.length];
    int i = 0;
    for (Certificate cert : xc) {
        xCerts[i++] = X509Certificate.getInstance(cert.getEncoded());
    }
}
 
Example #12
Source File: X509CertificateTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * @throws CertificateEncodingException
 * {@link Certificate#getEncoded()}
 */
public void testGetEncoded()
        throws CertificateEncodingException, java.security.cert.CertificateException {
    // cert = DER encoding of the ASN1.0 structure
    assertTrue(Arrays.equals(cert.getEncoded(), tbt_cert.getEncoded()));
    assertFalse(Arrays.equals(javaxCert.getEncoded(), tbt_cert.getEncoded()));
}
 
Example #13
Source File: OpenSslJavaxX509Certificate.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private X509Certificate unwrap() {
    X509Certificate wrapped = this.wrapped;
    if (wrapped == null) {
        try {
            wrapped = this.wrapped = X509Certificate.getInstance(bytes);
        } catch (CertificateException e) {
            throw new IllegalStateException(e);
        }
    }
    return wrapped;
}
 
Example #14
Source File: CertificateExceptionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Test for <code>CertificateException(String)</code> constructor
 * Assertion: constructs CertificateException when <code>msg</code> is
 * null
 */
public void testCertificateException03() {
    String msg = null;
    CertificateException tE = new CertificateException(msg);
    assertNull("getMessage() must return null.", tE.getMessage());
    assertNull("getCause() must return null", tE.getCause());
}
 
Example #15
Source File: CertificateExceptionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Test for <code>CertificateException()</code> constructor Assertion:
 * constructs CertificateException with no detail message
 */
public void testCertificateException01() {
    CertificateException tE = new CertificateException();
    assertNull("getMessage() must return null.", tE.getMessage());
    assertNull("getCause() must return null", tE.getCause());
}
 
Example #16
Source File: CertificateTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void verify(PublicKey key, String sigProvider)
        throws CertificateException, NoSuchAlgorithmException,
        InvalidKeyException, NoSuchProviderException,
        SignatureException {
}
 
Example #17
Source File: CertificateTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void verify(PublicKey key) throws CertificateException,
        NoSuchAlgorithmException, InvalidKeyException,
        NoSuchProviderException, SignatureException {
}
 
Example #18
Source File: X509CertificateTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Override
public void verify(PublicKey key, String sigProvider)
        throws CertificateException, NoSuchAlgorithmException,
        InvalidKeyException, NoSuchProviderException,
        SignatureException {
}
 
Example #19
Source File: X509CertificateTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Override
public void verify(PublicKey key) throws CertificateException,
        NoSuchAlgorithmException, InvalidKeyException,
        NoSuchProviderException, SignatureException {
}
 
Example #20
Source File: OpenSslJavaxX509Certificate.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Override
public void verify(PublicKey key)
        throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException,
               SignatureException {
    unwrap().verify(key);
}
 
Example #21
Source File: OpenSslJavaxX509Certificate.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Override
public void verify(PublicKey key, String sigProvider)
        throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException,
               SignatureException {
    unwrap().verify(key, sigProvider);
}
 
Example #22
Source File: BasicSSLSessionInfo.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 *
 * @param sessionId The Base64 encoded SSL session ID
 * @param cypherSuite The cypher suite name
 * @param certificate A string representation of the client certificate
 * @throws java.security.cert.CertificateException If the client cert could not be decoded
 * @throws CertificateException If the client cert could not be decoded
 */
public BasicSSLSessionInfo(String sessionId, String cypherSuite, String certificate) throws java.security.cert.CertificateException, CertificateException {
    this(sessionId == null ? null : base64Decode(sessionId), cypherSuite, certificate);
}
 
Example #23
Source File: BasicSSLSessionInfo.java    From quarkus-http with Apache License 2.0 2 votes vote down vote up
/**
 * @param sessionId   The Base64 encoded SSL session ID
 * @param cypherSuite The cypher suite name
 * @param certificate A string representation of the client certificate
 * @throws java.security.cert.CertificateException If the client cert could not be decoded
 * @throws CertificateException                    If the client cert could not be decoded
 */
public BasicSSLSessionInfo(String sessionId, String cypherSuite, String certificate) throws java.security.cert.CertificateException, CertificateException {
    this(sessionId == null ? null : base64Decode(sessionId), cypherSuite, certificate);
}