Search in sources :

Example 91 with X509Certificate

use of java.security.cert.X509Certificate in project netty by netty.

the class Base64Test method certFromString.

private static X509Certificate certFromString(String string) throws Exception {
    CertificateFactory factory = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream bin = new ByteArrayInputStream(string.getBytes(CharsetUtil.US_ASCII));
    try {
        return (X509Certificate) factory.generateCertificate(bin);
    } finally {
        bin.close();
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate)

Example 92 with X509Certificate

use of java.security.cert.X509Certificate in project netty by netty.

the class SslHandlerTest method testAlertProducedAndSend.

private void testAlertProducedAndSend(SslProvider provider) throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(provider).trustManager(new SimpleTrustManagerFactory() {

        @Override
        protected void engineInit(KeyStore keyStore) {
        }

        @Override
        protected void engineInit(ManagerFactoryParameters managerFactoryParameters) {
        }

        @Override
        protected TrustManager[] engineGetTrustManagers() {
            return new TrustManager[] { new X509TrustManager() {

                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    // Fail verification which should produce an alert that is send back to the client.
                    throw new CertificateException();
                }

                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
                // NOOP
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return EmptyArrays.EMPTY_X509_CERTIFICATES;
                }
            } };
        }
    }).clientAuth(ClientAuth.REQUIRE).build();
    final SslContext sslClientCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).keyManager(new File(getClass().getResource("test.crt").getFile()), new File(getClass().getResource("test_unencrypted.pem").getFile())).sslProvider(provider).build();
    NioEventLoopGroup group = new NioEventLoopGroup();
    Channel sc = null;
    Channel cc = null;
    try {
        final Promise<Void> promise = group.next().newPromise();
        sc = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast(sslServerCtx.newHandler(ch.alloc()));
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                        // Just trigger a close
                        ctx.close();
                    }
                });
            }
        }).bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
        cc = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast(sslClientCtx.newHandler(ch.alloc()));
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                        if (cause.getCause() instanceof SSLException) {
                            // We received the alert and so produce an SSLException.
                            promise.setSuccess(null);
                        }
                    }
                });
            }
        }).connect(sc.localAddress()).syncUninterruptibly().channel();
        promise.syncUninterruptibly();
    } finally {
        if (cc != null) {
            cc.close().syncUninterruptibly();
        }
        if (sc != null) {
            sc.close().syncUninterruptibly();
        }
        group.shutdownGracefully();
        ReferenceCountUtil.release(sslServerCtx);
        ReferenceCountUtil.release(sslClientCtx);
    }
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) InetSocketAddress(java.net.InetSocketAddress) CertificateException(java.security.cert.CertificateException) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) SSLException(javax.net.ssl.SSLException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) SimpleTrustManagerFactory(io.netty.handler.ssl.util.SimpleTrustManagerFactory) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) IllegalReferenceCountException(io.netty.util.IllegalReferenceCountException) CodecException(io.netty.handler.codec.CodecException) SSLProtocolException(javax.net.ssl.SSLProtocolException) DecoderException(io.netty.handler.codec.DecoderException) SSLException(javax.net.ssl.SSLException) ClosedChannelException(java.nio.channels.ClosedChannelException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) UnsupportedMessageTypeException(io.netty.handler.codec.UnsupportedMessageTypeException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) X509TrustManager(javax.net.ssl.X509TrustManager) File(java.io.File) ManagerFactoryParameters(javax.net.ssl.ManagerFactoryParameters) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 93 with X509Certificate

use of java.security.cert.X509Certificate in project netty by netty.

the class SslContextTrustManagerTest method runTests.

/**
     *
     * @param caResources
     *            an array of paths to CA Certificates in PEM format to load
     *            from the classpath (relative to this class).
     * @param eecResources
     *            an array of paths to Server Certificates in PEM format in to
     *            load from the classpath (relative to this class).
     * @param expectations
     *            an array of expecting results for each EEC Server Certificate
     *            (the array is expected to have the same length the previous
     *            argument, and be arrange in matching order: true means
     *            expected to be valid, false otherwise.
     */
private static void runTests(String[] caResources, String[] eecResources, boolean[] expectations) throws Exception {
    X509TrustManager tm = getTrustManager(caResources);
    X509Certificate[] eecCerts = loadCertCollection(eecResources);
    for (int i = 0; i < eecResources.length; i++) {
        X509Certificate eecCert = eecCerts[i];
        assertNotNull("Cannot use cert " + eecResources[i], eecCert);
        try {
            tm.checkServerTrusted(new X509Certificate[] { eecCert }, "RSA");
            if (!expectations[i]) {
                fail(String.format("Certificate %s was expected not to be valid when using CAs %s, but its " + "verification passed.", eecResources[i], Arrays.asList(caResources)));
            }
        } catch (CertificateException e) {
            if (expectations[i]) {
                fail(String.format("Certificate %s was expected to be valid when using CAs %s, but its " + "verification failed.", eecResources[i], Arrays.asList(caResources)));
            }
        }
    }
}
Also used : X509TrustManager(javax.net.ssl.X509TrustManager) CertificateException(java.security.cert.CertificateException) X509Certificate(java.security.cert.X509Certificate)

Example 94 with X509Certificate

use of java.security.cert.X509Certificate in project netty by netty.

the class SslContextTrustManagerTest method loadCertCollection.

private static X509Certificate[] loadCertCollection(String[] resourceNames) throws Exception {
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    X509Certificate[] certCollection = new X509Certificate[resourceNames.length];
    for (int i = 0; i < resourceNames.length; i++) {
        String resourceName = resourceNames[i];
        InputStream is = null;
        try {
            is = SslContextTest.class.getResourceAsStream(resourceName);
            assertNotNull("Cannot find " + resourceName, is);
            certCollection[i] = (X509Certificate) certFactory.generateCertificate(is);
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }
    return certCollection;
}
Also used : InputStream(java.io.InputStream) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate)

Example 95 with X509Certificate

use of java.security.cert.X509Certificate in project openhab1-addons by openhab.

the class AirConditioner method connect.

private void connect() throws Exception {
    if (isConnected()) {
        return;
    } else {
        logger.debug("Disconnected so we'll try again");
        disconnect();
    }
    if (CERTIFICATE_FILE_NAME != null && new File(CERTIFICATE_FILE_NAME).isFile()) {
        if (CERTIFICATE_PASSWORD == null) {
            CERTIFICATE_PASSWORD = "";
        }
        try {
            SSLClient client = new SSLClient();
            client.addTrustMaterial(TrustMaterial.DEFAULT);
            client.setCheckHostname(false);
            client.setKeyMaterial(new KeyMaterial(CERTIFICATE_FILE_NAME, CERTIFICATE_PASSWORD.toCharArray()));
            client.setConnectTimeout(10000);
            socket = (SSLSocket) client.createSocket(IP, PORT);
            socket.setSoTimeout(2000);
            socket.startHandshake();
        } catch (Exception e) {
            throw new Exception("Could not connect using certificate: " + CERTIFICATE_FILE_NAME, e);
        }
    } else {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                }
            } };
            ctx.init(null, trustAllCerts, null);
            socket = (SSLSocket) ctx.getSocketFactory().createSocket(IP, PORT);
            socket.setSoTimeout(2000);
            socket.startHandshake();
        } catch (Exception e) {
            throw new Exception("Cannot connect to " + IP + ":" + PORT, e);
        }
    }
    handleResponse();
}
Also used : SSLClient(org.apache.commons.ssl.SSLClient) KeyMaterial(org.apache.commons.ssl.KeyMaterial) X509TrustManager(javax.net.ssl.X509TrustManager) SSLContext(javax.net.ssl.SSLContext) File(java.io.File) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) SSLException(javax.net.ssl.SSLException) SocketTimeoutException(java.net.SocketTimeoutException) X509Certificate(java.security.cert.X509Certificate) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager)

Aggregations

X509Certificate (java.security.cert.X509Certificate)1706 IOException (java.io.IOException)336 CertificateException (java.security.cert.CertificateException)272 ByteArrayInputStream (java.io.ByteArrayInputStream)260 CertificateFactory (java.security.cert.CertificateFactory)251 ArrayList (java.util.ArrayList)232 Certificate (java.security.cert.Certificate)227 KeyStore (java.security.KeyStore)177 PrivateKey (java.security.PrivateKey)150 InputStream (java.io.InputStream)134 File (java.io.File)112 KeyStoreException (java.security.KeyStoreException)112 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)111 GeneralSecurityException (java.security.GeneralSecurityException)100 Test (org.junit.Test)90 List (java.util.List)89 PublicKey (java.security.PublicKey)88 X509TrustManager (javax.net.ssl.X509TrustManager)80 X500Principal (javax.security.auth.x500.X500Principal)76 HashSet (java.util.HashSet)64