javax.net.ssl.SSLEngine#setEnabledCipherSuites ( )源码实例Demo

下面列出了javax.net.ssl.SSLEngine#setEnabledCipherSuites ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: ovsdb   文件: OvsdbConnectionService.java
@Override
void initChannelImpl(final SocketChannel channel) {
    /* Add SSL handler first if SSL context is provided */
    final SSLContext sslContext = certManagerSrv.getServerContext();
    if (sslContext != null) {
        SSLEngine engine = sslContext.createSSLEngine();
        engine.setUseClientMode(false); // work in a server mode
        engine.setNeedClientAuth(true); // need client authentication
        if (protocols != null && protocols.length > 0) {
            //Set supported protocols
            engine.setEnabledProtocols(protocols);
            LOG.debug("Supported ssl protocols {}",
                Arrays.toString(engine.getSupportedProtocols()));
            LOG.debug("Enabled ssl protocols {}",
                Arrays.toString(engine.getEnabledProtocols()));
        }
        if (cipherSuites != null && cipherSuites.length > 0) {
            //Set supported cipher suites
            engine.setEnabledCipherSuites(cipherSuites);
            LOG.debug("Enabled cipher suites {}",
                Arrays.toString(engine.getEnabledCipherSuites()));
        }
        channel.pipeline().addLast("ssl", new SslHandler(engine));
    }
    super.initChannelImpl(channel);
}
 
源代码2 项目: qpid-jms   文件: TransportSupport.java
/**
 * Create a new JDK SSLEngine instance in client mode from the given SSLContext and
 * TransportOptions instances.
 *
 * @param remote
 *        the URI of the remote peer that will be used to initialize the engine, may be null if none should.
 * @param context
 *        the SSLContext to use when creating the engine.
 * @param options
 *        the TransportOptions to use to configure the new SSLEngine.
 *
 * @return a new SSLEngine instance in client mode.
 *
 * @throws Exception if an error occurs while creating the new SSLEngine.
 */
public static SSLEngine createJdkSslEngine(URI remote, SSLContext context, TransportOptions options) throws Exception {
    SSLEngine engine = null;
    if (remote == null) {
        engine = context.createSSLEngine();
    } else {
        engine = context.createSSLEngine(remote.getHost(), remote.getPort());
    }

    engine.setEnabledProtocols(buildEnabledProtocols(engine, options));
    engine.setEnabledCipherSuites(buildEnabledCipherSuites(engine, options));
    engine.setUseClientMode(true);

    if (options.isVerifyHost()) {
        SSLParameters sslParameters = engine.getSSLParameters();
        sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
        engine.setSSLParameters(sslParameters);
    }

    return engine;
}
 
源代码3 项目: openjdk-jdk9   文件: DTLSIncorrectAppDataTest.java
@Override
protected void testOneCipher(String cipher) {
    SSLContext context = getContext();
    int maxPacketSize = getMaxPacketSize();
    boolean useSNI = !TEST_MODE.equals("norm");
    SSLEngine clientEngine = getClientSSLEngine(context, useSNI);
    SSLEngine serverEngine = getServerSSLEngine(context, useSNI);
    clientEngine.setEnabledCipherSuites(new String[]{cipher});
    serverEngine.setEnabledCipherSuites(new String[]{cipher});
    serverEngine.setNeedClientAuth(!cipher.contains("anon"));
    try {
        doHandshake(clientEngine, serverEngine, maxPacketSize,
                HandshakeMode.INITIAL_HANDSHAKE);
        checkIncorrectAppDataUnwrap(clientEngine, serverEngine);
        checkIncorrectAppDataUnwrap(serverEngine, clientEngine);
    } catch (SSLException ssle) {
        throw new AssertionError("Error during handshake or sending app data",
                ssle);
    }
}
 
@Override
protected void testOneCipher(String cipher) throws SSLException {
    SSLContext context = getContext();
    int maxPacketSize = getMaxPacketSize();
    boolean useSNI = !TEST_MODE.equals("norm");
    SSLEngine clientEngine = getClientSSLEngine(context, useSNI);
    SSLEngine serverEngine = getServerSSLEngine(context, useSNI);
    clientEngine.setEnabledCipherSuites(new String[]{cipher});
    serverEngine.setEnabledCipherSuites(new String[]{cipher});
    serverEngine.setNeedClientAuth(!cipher.contains("anon"));
    doHandshake(clientEngine, serverEngine, maxPacketSize,
            HandshakeMode.INITIAL_HANDSHAKE);
    checkBufferOverflowOnWrap(clientEngine);
    checkBufferOverflowOnWrap(serverEngine);
    checkBufferOverflowOnUnWrap(clientEngine, serverEngine);
    checkBufferOverflowOnUnWrap(serverEngine, clientEngine);
    checkBufferUnderflowOnUnWrap(serverEngine, clientEngine);
    checkBufferUnderflowOnUnWrap(clientEngine, serverEngine);
}
 
源代码5 项目: netty-4.1.22   文件: JdkSslContext.java
@SuppressWarnings("deprecation")
private SSLEngine configureAndWrapEngine(SSLEngine engine, ByteBufAllocator alloc) {
    engine.setEnabledCipherSuites(cipherSuites);
    engine.setEnabledProtocols(protocols);
    engine.setUseClientMode(isClient());
    if (isServer()) {
        switch (clientAuth) {
            case OPTIONAL:
                engine.setWantClientAuth(true);
                break;
            case REQUIRE:
                engine.setNeedClientAuth(true);
                break;
            case NONE:
                break; // exhaustive cases
            default:
                throw new Error("Unknown auth " + clientAuth);
        }
    }
    JdkApplicationProtocolNegotiator.SslEngineWrapperFactory factory = apn.wrapperFactory();
    if (factory instanceof JdkApplicationProtocolNegotiator.AllocatorAwareSslEngineWrapperFactory) {
        return ((JdkApplicationProtocolNegotiator.AllocatorAwareSslEngineWrapperFactory) factory)
                .wrapSslEngine(engine, alloc, apn, isServer());
    }
    return factory.wrapSslEngine(engine, apn, isServer());
}
 
源代码6 项目: NetBare   文件: SSLEngineFactory.java
/**
 * Create a client {@link SSLEngine} with the remote server IP and port.
 *
 * @param host Remote server host.
 * @param port Remote server port.
 * @return A client {@link SSLEngine} instance.
 * @throws ExecutionException If an execution error has occurred.
 */
public SSLEngine createClientEngine(@NonNull final String host, int port) throws ExecutionException {
    SSLContext ctx = CLIENT_SSL_CONTEXTS.get(host, new Callable<SSLContext>() {
        @Override
        public SSLContext call() throws GeneralSecurityException, IOException,
                OperatorCreationException {
            return createClientContext(host);
        }
    });
    SSLEngine engine = ctx.createSSLEngine(host, port);
    List<String> ciphers = new LinkedList<>();
    for (String each : engine.getEnabledCipherSuites()) {
        if (!each.equals("TLS_DHE_RSA_WITH_AES_128_CBC_SHA") &&
                !each.equals("TLS_DHE_RSA_WITH_AES_256_CBC_SHA")) {
            ciphers.add(each);
        }
    }
    engine.setEnabledCipherSuites(ciphers.toArray(new String[0]));
    engine.setUseClientMode(true);
    engine.setNeedClientAuth(false);
    return engine;
}
 
源代码7 项目: iotplatform   文件: MqttSslHandlerProvider.java
public SslHandler getSslHandler() {
    try {
        URL ksUrl = Resources.getResource(keyStoreFile);
        File ksFile = new File(ksUrl.toURI());
        URL tsUrl = Resources.getResource(keyStoreFile);
        File tsFile = new File(tsUrl.toURI());

        TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore trustStore = KeyStore.getInstance(keyStoreType);
        trustStore.load(new FileInputStream(tsFile), keyStorePassword.toCharArray());
        tmFactory.init(trustStore);

        KeyStore ks = KeyStore.getInstance(keyStoreType);

        ks.load(new FileInputStream(ksFile), keyStorePassword.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, keyPassword.toCharArray());

        KeyManager[] km = kmf.getKeyManagers();
        TrustManager x509wrapped = getX509TrustManager(tmFactory);
        TrustManager[] tm = {x509wrapped};
        SSLContext sslContext = SSLContext.getInstance(TLS);
        sslContext.init(km, tm, null);
        SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(false);
        sslEngine.setNeedClientAuth(false);
        sslEngine.setWantClientAuth(true);
        sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
        sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
        sslEngine.setEnableSessionCreation(true);
        return new SslHandler(sslEngine);
    } catch (Exception e) {
        log.error("Unable to set up SSL context. Reason: " + e.getMessage(), e);
        throw new RuntimeException("Failed to get SSL handler", e);
    }
}
 
源代码8 项目: IoTgo_Android_App   文件: SslContextFactory.java
public void customize(SSLEngine sslEngine)
{
    if (getWantClientAuth())
        sslEngine.setWantClientAuth(getWantClientAuth());
    if (getNeedClientAuth())
        sslEngine.setNeedClientAuth(getNeedClientAuth());

    sslEngine.setEnabledCipherSuites(selectCipherSuites(
            sslEngine.getEnabledCipherSuites(),
            sslEngine.getSupportedCipherSuites()));

    sslEngine.setEnabledProtocols(selectProtocols(sslEngine.getEnabledProtocols(),sslEngine.getSupportedProtocols()));
}
 
源代码9 项目: IoTgo_Android_App   文件: SslContextFactory.java
public void customize(SSLEngine sslEngine)
{
    if (getWantClientAuth())
        sslEngine.setWantClientAuth(getWantClientAuth());
    if (getNeedClientAuth())
        sslEngine.setNeedClientAuth(getNeedClientAuth());

    sslEngine.setEnabledCipherSuites(selectCipherSuites(
            sslEngine.getEnabledCipherSuites(),
            sslEngine.getSupportedCipherSuites()));

    sslEngine.setEnabledProtocols(selectProtocols(sslEngine.getEnabledProtocols(),sslEngine.getSupportedProtocols()));
}
 
源代码10 项目: onos   文件: OFChannelInitializer.java
@Override
protected void initChannel(SocketChannel ch) throws Exception {

    OFChannelHandler handler = new OFChannelHandler(controller);

    ChannelPipeline pipeline = ch.pipeline();
    if (sslContext != null) {
        log.info("OpenFlow SSL enabled.");
        SSLEngine sslEngine = sslContext.createSSLEngine();

        sslEngine.setNeedClientAuth(true);
        sslEngine.setUseClientMode(false);
        sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
        sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
        sslEngine.setEnableSessionCreation(true);

        SslHandler sslHandler = new SslHandler(sslEngine);
        pipeline.addLast("ssl", sslHandler);
    } else {
        log.debug("OpenFlow SSL disabled.");
    }
    pipeline.addLast("ofmessageencoder", OFMessageEncoder.getInstance());
    pipeline.addLast("ofmessagedecoder", OFMessageDecoder.getInstance());

    pipeline.addLast("consolidateflush", new FlushConsolidationHandler(
                       FlushConsolidationHandler.DEFAULT_EXPLICIT_FLUSH_AFTER_FLUSHES, true));
    pipeline.addLast("idle", new IdleStateHandler(5, 25, 0));
    pipeline.addLast("timeout", new ReadTimeoutHandler(30));

    // XXX S ONOS: was 15 increased it to fix Issue #296
    pipeline.addLast("handshaketimeout",
                     new HandshakeTimeoutHandler(handler, 60));
    // ExecutionHandler equivalent now part of Netty core
    if (pipelineExecutor != null) {
        pipeline.addLast(pipelineExecutor, "handler", handler);
    } else {
        pipeline.addLast("handler", handler);
    }
}
 
源代码11 项目: openjdk-jdk9   文件: UnsupportedCiphersTest.java
private void unsupTest(String cipher, boolean clientTest) {
    SSLContext context = getContext();
    SSLEngine clientEngine = context.createSSLEngine();
    clientEngine.setUseClientMode(true);
    SSLEngine serverEngine = context.createSSLEngine();
    serverEngine.setUseClientMode(false);
    if (clientTest) {
        clientEngine.setEnabledCipherSuites(new String[]{cipher});
    } else {
        serverEngine.setEnabledCipherSuites(new String[]{cipher});
    }
}
 
源代码12 项目: FoxTelem   文件: ExportControlled.java
public static AsynchronousSocketChannel startTlsOnAsynchronousChannel(AsynchronousSocketChannel channel, SocketConnection socketConnection)
        throws SSLException {

    PropertySet propertySet = socketConnection.getPropertySet();

    SslMode sslMode = propertySet.<SslMode> getEnumProperty(PropertyKey.sslMode).getValue();

    boolean verifyServerCert = sslMode == SslMode.VERIFY_CA || sslMode == SslMode.VERIFY_IDENTITY;
    KeyStoreConf trustStore = !verifyServerCert ? new KeyStoreConf() : getTrustStoreConf(propertySet, PropertyKey.trustCertificateKeyStoreUrl,
            PropertyKey.trustCertificateKeyStorePassword, PropertyKey.trustCertificateKeyStoreType, true);

    KeyStoreConf keyStore = getKeyStoreConf(propertySet, PropertyKey.clientCertificateKeyStoreUrl, PropertyKey.clientCertificateKeyStorePassword,
            PropertyKey.clientCertificateKeyStoreType);

    SSLContext sslContext = ExportControlled.getSSLContext(keyStore.keyStoreUrl, keyStore.keyStoreType, keyStore.keyStorePassword, trustStore.keyStoreUrl,
            trustStore.keyStoreType, trustStore.keyStorePassword, false, verifyServerCert,
            sslMode == PropertyDefinitions.SslMode.VERIFY_IDENTITY ? socketConnection.getHost() : null, null);
    SSLEngine sslEngine = sslContext.createSSLEngine();
    sslEngine.setUseClientMode(true);

    sslEngine.setEnabledProtocols(getAllowedProtocols(propertySet, null, sslEngine.getSupportedProtocols()));

    String[] allowedCiphers = getAllowedCiphers(propertySet, null, sslEngine.getEnabledCipherSuites());
    if (allowedCiphers != null) {
        sslEngine.setEnabledCipherSuites(allowedCiphers);
    }

    performTlsHandshake(sslEngine, channel);

    return new TlsAsynchronousSocketChannel(channel, sslEngine);
}
 
源代码13 项目: qpid-proton-j   文件: SslEngineFacadeFactory.java
private void addAnonymousCipherSuites(SSLEngine sslEngine)
{
    List<String> supportedSuites = Arrays.asList(sslEngine.getSupportedCipherSuites());
    List<String> currentEnabledSuites = Arrays.asList(sslEngine.getEnabledCipherSuites());

    List<String> enabledSuites = buildEnabledSuitesIncludingAnonymous(ANONYMOUS_CIPHER_SUITES, supportedSuites, currentEnabledSuites);
    sslEngine.setEnabledCipherSuites(enabledSuites.toArray(new String[0]));
}
 
源代码14 项目: stratio-cassandra   文件: Server.java
protected void initChannel(Channel channel) throws Exception
{
    SSLEngine sslEngine = sslContext.createSSLEngine();
    sslEngine.setUseClientMode(false);
    sslEngine.setEnabledCipherSuites(encryptionOptions.cipher_suites);
    sslEngine.setNeedClientAuth(encryptionOptions.require_client_auth);
    sslEngine.setEnabledProtocols(SSLFactory.ACCEPTED_PROTOCOLS);
    SslHandler sslHandler = new SslHandler(sslEngine);
    super.initChannel(channel);
    channel.pipeline().addFirst("ssl", sslHandler);
}
 
源代码15 项目: openjdk-jdk9   文件: HandshakeTest.java
@Override
protected void testOneCipher(String cipher) throws SSLException {
    SSLContext context = getContext();
    int maxPacketSize = getMaxPacketSize();
    boolean useSNI = !TEST_MODE.equals("norm");
    SSLEngine clientEngine = getClientSSLEngine(context, useSNI);
    SSLEngine serverEngine = getServerSSLEngine(context, useSNI);
    clientEngine.setEnabledCipherSuites(new String[]{cipher});
    serverEngine.setEnabledCipherSuites(new String[]{cipher});
    serverEngine.setNeedClientAuth(!cipher.contains("anon"));
    doHandshake(clientEngine, serverEngine, maxPacketSize,
            HandshakeMode.INITIAL_HANDSHAKE);
}
 
源代码16 项目: Tomcat8-Source-Read   文件: AbstractJsseEndpoint.java
protected SSLEngine createSSLEngine(String sniHostName, List<Cipher> clientRequestedCiphers,
        List<String> clientRequestedApplicationProtocols) {
    SSLHostConfig sslHostConfig = getSSLHostConfig(sniHostName);

    SSLHostConfigCertificate certificate = selectCertificate(sslHostConfig, clientRequestedCiphers);

    SSLContext sslContext = certificate.getSslContext();
    if (sslContext == null) {
        throw new IllegalStateException(
                sm.getString("endpoint.jsse.noSslContext", sniHostName));
    }

    SSLEngine engine = sslContext.createSSLEngine();
    engine.setUseClientMode(false);
    engine.setEnabledCipherSuites(sslHostConfig.getEnabledCiphers());
    engine.setEnabledProtocols(sslHostConfig.getEnabledProtocols());

    SSLParameters sslParameters = engine.getSSLParameters();
    String honorCipherOrderStr = sslHostConfig.getHonorCipherOrder();
    if (honorCipherOrderStr != null) {
        boolean honorCipherOrder = Boolean.parseBoolean(honorCipherOrderStr);
        JreCompat.getInstance().setUseServerCipherSuitesOrder(sslParameters, honorCipherOrder);
    }

    if (JreCompat.isJre9Available() && clientRequestedApplicationProtocols != null
            && clientRequestedApplicationProtocols.size() > 0
            && negotiableProtocols.size() > 0) {
        // Only try to negotiate if both client and server have at least
        // one protocol in common
        // Note: Tomcat does not explicitly negotiate http/1.1
        // TODO: Is this correct? Should it change?
        List<String> commonProtocols = new ArrayList<>();
        commonProtocols.addAll(negotiableProtocols);
        commonProtocols.retainAll(clientRequestedApplicationProtocols);
        if (commonProtocols.size() > 0) {
            String[] commonProtocolsArray = commonProtocols.toArray(new String[commonProtocols.size()]);
            JreCompat.getInstance().setApplicationProtocols(sslParameters, commonProtocolsArray);
        }
    }
    switch (sslHostConfig.getCertificateVerification()) {
    case NONE:
        sslParameters.setNeedClientAuth(false);
        sslParameters.setWantClientAuth(false);
        break;
    case OPTIONAL:
    case OPTIONAL_NO_CA:
        sslParameters.setWantClientAuth(true);
        break;
    case REQUIRED:
        sslParameters.setNeedClientAuth(true);
        break;
    }
    // The getter (at least in OpenJDK and derivatives) returns a defensive copy
    engine.setSSLParameters(sslParameters);

    return engine;
}
 
源代码17 项目: arcusplatform   文件: VideoRecordingServer.java
@Override
public void initChannel(@Nullable SocketChannel ch) throws Exception {
   try {
      Preconditions.checkNotNull(ch);

      ChannelPipeline pipeline = ch.pipeline();

      pipeline.addLast(new IPTrackingInboundHandler());

      TrafficHandler trafficHandler = trafficHandlerProvider.get();
      if (trafficHandler != null) {
         pipeline.addLast(trafficHandler);
      }

      if (videoConfig.isTls()) {
         SSLEngine engine = serverTlsContext.getContext().newEngine(ch.alloc());
         engine.setWantClientAuth(true);
         engine.setNeedClientAuth(false);
         engine.setUseClientMode(false);

         engine.setEnabledCipherSuites(engine.getSupportedCipherSuites());
         engine.setEnabledProtocols(engine.getSupportedProtocols());

         SslHandler handler = new SslHandler(engine);
         handler.setHandshakeTimeout(videoConfig.getRecordingSslHandshakeTimeout(), TimeUnit.SECONDS);
         handler.setCloseNotifyTimeout(videoConfig.getRecordingSslCloseNotifyTimeout(), TimeUnit.SECONDS);

         pipeline.addLast(handler);
      }

      pipeline.addLast(new VideoRecordingSessionTimer());

      long readIdleTimeout = videoConfig.getReadIdleTimeout();
      if (readIdleTimeout > 0) {
         pipeline.addLast(new IdleStateHandler(readIdleTimeout,0L,0L,TimeUnit.SECONDS));
      }

      pipeline.addLast(new RtspPushHandler());
      pipeline.addLast(new RtspInterleavedHandler());
      pipeline.addLast(new RtpHandler());
      pipeline.addLast(new RtcpHandler());
      pipeline.addLast(new RtpH264Handler(factory, registry));
      pipeline.addLast(new RtpFinalHandler(registry));
      pipeline.addLast(new IPTrackingOutboundHandler());

      RECORDING_START_SUCCESS.inc();
   } catch (Throwable th) {
      RECORDING_START_FAIL.inc();
      throw th;
   }
}
 
源代码18 项目: arcusplatform   文件: Bridge10ChannelInitializer.java
@Override
protected void initChannel(SocketChannel ch) throws Exception {
   ChannelPipeline pipeline = ch.pipeline();
   pipeline.addLast(inboundIpTracking);

   TrafficHandler trafficHandler = trafficHandlerProvider.get();
   if (trafficHandler != null) {
      pipeline.addLast(trafficHandler);
   }

   if (serverTlsContext != null && serverTlsContext.useTls()) {
      metrics.onAccepted();

      final long startTimeNs = metrics.startTime();
      SslContext sslCtx = serverTlsContext.getContext();

      final SSLEngine engine = SslMetrics.instrument(sslCtx.newEngine(ch.alloc()));

      if (ciphers.length > 0) { 
         engine.setEnabledCipherSuites(ciphers);
      } else {
         engine.setEnabledCipherSuites(engine.getSupportedCipherSuites());
      }

      if (protocols.length > 0) {
         engine.setEnabledProtocols(protocols);
      } else {
         engine.setEnabledProtocols(engine.getSupportedProtocols());
      }

      SSLParameters params = engine.getSSLParameters();
      params.setUseCipherSuitesOrder(true);
      engine.setSSLParameters(params);

      SslHandler handler = new SslHandler(engine);

      handler.setHandshakeTimeout(serverConfig.getTlsHandshakeTimeoutSec(), TimeUnit.SECONDS);
      handler.setCloseNotifyTimeout(serverConfig.getTlsCloseNotifyTimeoutSec(), TimeUnit.SECONDS);
      handler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {
         @Override
         public void operationComplete(Future<Channel> future) throws Exception {
            if(future.isSuccess()) {
               metrics.onHandshakeSuccess(startTimeNs);

               SSLSession session = engine.getSession();
               logger.info("ssl handler finished: protocol={}, cipher={}", session.getProtocol(), session.getCipherSuite());
            }
            else {
               metrics.onHandshakeFailure(startTimeNs);
            }
         }
      });

      pipeline.addLast(FILTER_SSL, handler);
   }

   pipeline.addLast(FILTER_ENCODER, new HttpResponseEncoder());
   pipeline.addLast(FILTER_DECODER, new HttpRequestDecoder());
   pipeline.addLast(FILTER_HTTP_AGGREGATOR, new HttpObjectAggregator(65536));
   if (bindClientHandler != null) {
      pipeline.addLast("bind-client-context", bindClientHandler);
   }
   pipeline.addLast("clear-client-context", clearClientHandler);
   pipeline.addLast(IDLE_STATE_HANDLER, new IdleStateHandler(serverConfig.getWebSocketPongTimeout(), serverConfig.getWebSocketPingRate(), 0));
   pipeline.addLast(CHUNKED_WRITE_HANDLER, new ChunkedWriteHandler());
   pipeline.addLast(FILTER_HANDLER, channelInboundProvider.get());
   pipeline.addLast(outboundIpTracking);
}
 
@Override
protected void testOneCipher(String cipher) throws SSLException {
    SSLContext context = getContext();
    int maxPacketSize = getMaxPacketSize();
    SSLEngine clientEngine = context.createSSLEngine();
    clientEngine.setUseClientMode(true);
    SSLEngine serverEngine = context.createSSLEngine();
    serverEngine.setUseClientMode(false);
    clientEngine.setEnabledCipherSuites(new String[]{cipher});
    serverEngine.setEnabledCipherSuites(
            Ciphers.ENABLED_NON_KRB_NOT_ANON_CIPHERS.ciphers);
    String randomCipher;
    serverEngine.setNeedClientAuth(true);
    long initialEpoch = 0;
    long secondEpoch = 0;
    SSLEngineResult r;
    doHandshake(clientEngine, serverEngine, maxPacketSize,
            HandshakeMode.INITIAL_HANDSHAKE);
    sendApplicationData(clientEngine, serverEngine);
    r = sendApplicationData(serverEngine, clientEngine);
    if (TESTED_SECURITY_PROTOCOL.contains("DTLS")) {
        initialEpoch = r.sequenceNumber() >> 48;
    }
    final Random RNG = RandomFactory.getRandom();
    randomCipher = Ciphers.ENABLED_NON_KRB_NOT_ANON_CIPHERS.ciphers[RNG
            .nextInt(Ciphers.ENABLED_NON_KRB_NOT_ANON_CIPHERS.ciphers.length)];
    clientEngine.setEnabledCipherSuites(new String[]{randomCipher});
    doHandshake(clientEngine, serverEngine, maxPacketSize,
            HandshakeMode.REHANDSHAKE_BEGIN_CLIENT);
    sendApplicationData(clientEngine, serverEngine);
    r = sendApplicationData(serverEngine, clientEngine);
    if (TESTED_SECURITY_PROTOCOL.contains("DTLS")) {
        secondEpoch = r.sequenceNumber() >> 48;
        AssertionError epochError = new AssertionError("Epoch number"
                + " did not grow after re-handshake! "
                + " Was " + initialEpoch + ", now " + secondEpoch + ".");
        if (Long.compareUnsigned(secondEpoch, initialEpoch) <= 0) {
            throw epochError;
        }
    }
    closeEngines(clientEngine, serverEngine);
}
 
源代码20 项目: openjdk-jdk9   文件: RehandshakeWithDataExTest.java
@Override
protected void testOneCipher(String cipher) throws SSLException {
    SSLContext context = getContext();
    int maxPacketSize = getMaxPacketSize();
    boolean useSNI = !TEST_MODE.equals("norm");
    SSLEngine clientEngine = getClientSSLEngine(context, useSNI);
    SSLEngine serverEngine = getServerSSLEngine(context, useSNI);
    clientEngine.setEnabledCipherSuites(new String[]{cipher});
    serverEngine.setEnabledCipherSuites(new String[]{cipher});
    serverEngine.setNeedClientAuth(!cipher.contains("anon"));
    long initialEpoch = 0;
    long secondEpoch = 0;
    long thirdEpoch = 0;
    SSLEngineResult r;
    doHandshake(clientEngine, serverEngine, maxPacketSize,
            HandshakeMode.INITIAL_HANDSHAKE);
    sendApplicationData(clientEngine, serverEngine);
    r = sendApplicationData(serverEngine, clientEngine);
    if (TESTED_SECURITY_PROTOCOL.contains("DTLS")) {
        initialEpoch = r.sequenceNumber() >> 48;
    }
    doHandshake(clientEngine, serverEngine, maxPacketSize,
            HandshakeMode.REHANDSHAKE_BEGIN_CLIENT);
    sendApplicationData(clientEngine, serverEngine);
    r = sendApplicationData(serverEngine, clientEngine);
    AssertionError epochError = new AssertionError("Epoch number"
            + " did not grow after re-handshake! "
            + " Was " + initialEpoch + ", now " + secondEpoch + ".");
    if (TESTED_SECURITY_PROTOCOL.contains("DTLS")) {
        secondEpoch = r.sequenceNumber() >> 48;
        if (Long.compareUnsigned(secondEpoch, initialEpoch) <= 0) {
            throw epochError;
        }
    }
    doHandshake(clientEngine, serverEngine, maxPacketSize,
            HandshakeMode.REHANDSHAKE_BEGIN_SERVER);
    sendApplicationData(clientEngine, serverEngine);
    r = sendApplicationData(serverEngine, clientEngine);
    if (TESTED_SECURITY_PROTOCOL.contains("DTLS")) {
    thirdEpoch = r.sequenceNumber() >> 48;
        if (Long.compareUnsigned(thirdEpoch, secondEpoch) <= 0) {
            throw epochError;
        }
    }
    closeEngines(clientEngine, serverEngine);
}