Java源码示例:javax.security.cert.CertificateException

示例1
@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);
}
 
示例2
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);
    }
}
 
示例3
/**
 * 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);
    }
}
 
示例4
@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;
}
 
示例5
/**
 * 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();
}
 
示例6
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;
}
 
示例7
/**
 *  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;
}
 
示例8
@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);
}
 
示例9
/**
 * @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()));
}
 
示例10
/**
 * 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());
}
 
示例11
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());
    }
}
 
示例12
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);
    }
}
 
示例13
/**
 * 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();
}
 
示例14
/**
 * 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();
}
 
示例15
@Override
public void verify(PublicKey key)
        throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException,
               SignatureException {
    unwrap().verify(key);
}
 
示例16
@Override
public void verify(PublicKey key, String sigProvider)
        throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException,
               SignatureException {
    unwrap().verify(key, sigProvider);
}
 
示例17
@Override
public void verify(PublicKey key) throws CertificateException,
        NoSuchAlgorithmException, InvalidKeyException,
        NoSuchProviderException, SignatureException {
}
 
示例18
@Override
public void verify(PublicKey key, String sigProvider)
        throws CertificateException, NoSuchAlgorithmException,
        InvalidKeyException, NoSuchProviderException,
        SignatureException {
}
 
示例19
/**
 * 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());
}
 
示例20
public void verify(PublicKey key) throws CertificateException,
        NoSuchAlgorithmException, InvalidKeyException,
        NoSuchProviderException, SignatureException {
}
 
示例21
public void verify(PublicKey key, String sigProvider)
        throws CertificateException, NoSuchAlgorithmException,
        InvalidKeyException, NoSuchProviderException,
        SignatureException {
}
 
示例22
/**
 * @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);
}
 
示例23
/**
 *
 * @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);
}