Path: blob/master/test/jdk/javax/net/ssl/TLS/CipherTestUtils.java
41152 views
/*1* Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import java.io.ByteArrayInputStream;24import java.io.EOFException;25import java.io.File;26import java.io.FileInputStream;27import java.io.FileNotFoundException;28import java.io.IOException;29import java.io.InputStream;30import java.io.OutputStream;31import java.net.Socket;32import java.security.KeyFactory;33import java.security.KeyStore;34import java.security.KeyStoreException;35import java.security.NoSuchAlgorithmException;36import java.security.Principal;37import java.security.PrivateKey;38import java.security.SecureRandom;39import java.security.UnrecoverableKeyException;40import java.security.cert.Certificate;41import java.security.cert.CertificateException;42import java.security.cert.CertificateFactory;43import java.security.cert.X509Certificate;44import java.security.interfaces.RSAPrivateKey;45import java.security.spec.InvalidKeySpecException;46import java.security.spec.PKCS8EncodedKeySpec;47import java.util.ArrayList;48import java.util.Arrays;49import java.util.Base64;50import java.util.Collections;51import java.util.List;52import javax.net.ssl.KeyManagerFactory;53import javax.net.ssl.SSLEngine;54import javax.net.ssl.SSLServerSocket;55import javax.net.ssl.SSLSocket;56import javax.net.ssl.SSLSocketFactory;57import javax.net.ssl.TrustManager;58import javax.net.ssl.TrustManagerFactory;59import javax.net.ssl.X509ExtendedKeyManager;60import javax.net.ssl.X509TrustManager;6162/**63* Test that all ciphersuites work in all versions and all client authentication64* types. The way this is setup the server is stateless and all checking is done65* on the client side.66*/6768public class CipherTestUtils {6970public static final int TIMEOUT = 20 * 1000;71public static final SecureRandom secureRandom = new SecureRandom();72public static char[] PASSWORD = "passphrase".toCharArray();73private static final List<TestParameters> TESTS = new ArrayList<>(3);74private static final List<Exception> EXCEPTIONS75= Collections.synchronizedList(new ArrayList<>(1));7677private static final String CLIENT_PUBLIC_KEY78= "-----BEGIN CERTIFICATE-----\n"79+ "MIICtTCCAh4CCQDkYJ46DMcGRjANBgkqhkiG9w0BAQUFADCBnDELMAkGA1UEBhMC\n"80+ "VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MR8wHQYDVQQK\n"81+ "DBZTdW4gTWljcm9zeXN0ZW1zLCBJbmMuMSYwJAYDVQQLDB1TdW4gTWljcm9zeXN0\n"82+ "ZW1zIExhYm9yYXRvcmllczEfMB0GA1UEAwwWVGVzdCBDQSAoMTAyNCBiaXQgUlNB\n"83+ "KTAeFw0wOTA0MjcwNDA0MDhaFw0xMzA2MDUwNDA0MDhaMIGgMQswCQYDVQQGEwJV\n"84+ "UzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxHzAdBgNVBAoM\n"85+ "FlN1biBNaWNyb3N5c3RlbXMsIEluYy4xJjAkBgNVBAsMHVN1biBNaWNyb3N5c3Rl\n"86+ "bXMgTGFib3JhdG9yaWVzMSMwIQYDVQQDDBpUZXN0IENsaWVudCAoMTAyNCBiaXQg\n"87+ "UlNBKTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAm5rwjmhO7Nwd5GWs+KvQ\n"88+ "UnDiqpRDvRriOUFdF0rCI2Op24C+iwUMDGxPsgP7VkUpOdJhw3c72aP0CAWcZ5dN\n"89+ "UCW7WVDAxnogCahLCir1jjoGdEjiNGOy0L9sypsM9UvBzJN8uvXsxsTZX4Z88cKU\n"90+ "G7RUvN8LQ88zDljk5zr3c2MCAwEAATANBgkqhkiG9w0BAQUFAAOBgQA7LUDrzHln\n"91+ "EXuGmwZeeroACB6DVtkClMskF/Pj5GnTxoeNN9DggycX/eOeIDKRloHuMpBeZPJH\n"92+ "NUwFu4LB6HBDeldQD9iRp8zD/fPakOdN+1Gk5hciIZZJ5hQmeCl7Va2Gr64vUqZG\n"93+ "MkVU755t+7ByLgzWuhPhhsX9QCuPR5FjvQ==\n"94+ "-----END CERTIFICATE-----";9596private static final String CLIENT_PRIVATE_KEY97= "-----BEGIN PRIVATE KEY-----\n"98+ "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJua8I5oTuzcHeRl\n"99+ "rPir0FJw4qqUQ70a4jlBXRdKwiNjqduAvosFDAxsT7ID+1ZFKTnSYcN3O9mj9AgF\n"100+ "nGeXTVAlu1lQwMZ6IAmoSwoq9Y46BnRI4jRjstC/bMqbDPVLwcyTfLr17MbE2V+G\n"101+ "fPHClBu0VLzfC0PPMw5Y5Oc693NjAgMBAAECgYA5w73zj8Nk6J3sMNaShe3S/PcY\n"102+ "TewLopRCnwI46FbDnnbq9pNFtnzvi7HWKuY983THc1M5peTA+b1Y0QRr7F4Vg4x9\n"103+ "9UM0B/tZcIIcJJ3LS+9fXKCbYLQWq5F05JqeZu+i+QLmJFO5+2p7laeQ4oQfW7QE\n"104+ "YR4u2mSaLe0SsqHvOQJBAMhgcye9C6pJO0eo2/VtRxAXI7zxNAIjHwKo1cva7bhu\n"105+ "GdrMaEAJBAsMJ1GEk7/WDI+3KEbTjQdfIJuAvOR4FXUCQQDGzNn/tl2k93v/ugyM\n"106+ "/tBhCKDipYDIbyJMoG2AOtOGmCsiGo5L7idO4OAcm/QiHBQMXjFIVgTUcH8MhGj4\n"107+ "blJ3AkA5fUqsxRV6tuYWKkFpif/QgwMS65VDY7Y6+hvVECwSNSyf1PO4I54QWV1S\n"108+ "ixok+RHDjgY1Q+77hXSCiQ4o8rcdAkBHvjfR+5sx5IpgUGElJPRIgFenU3j1XH3x\n"109+ "T1gVFaWuhg3S4eiGaGzRH4BhcrqY8K8fg4Kfi0N08yA2gTZsqUujAkEAjuNPTuKx\n"110+ "ti0LXI09kbGUqOpRMm1zW5TD6LFeEaUN6oxrSZI2YUvu7VyotAqsxX5O0u0f3VQw\n"111+ "ySF0Q1oZ6qu7cg==\n"112+ "-----END PRIVATE KEY-----";113private static final String SERVER_PUBLIC_KEY114= "-----BEGIN CERTIFICATE-----\n"115+ "MIICtTCCAh4CCQDkYJ46DMcGRTANBgkqhkiG9w0BAQUFADCBnDELMAkGA1UEBhMC\n"116+ "VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MR8wHQYDVQQK\n"117+ "DBZTdW4gTWljcm9zeXN0ZW1zLCBJbmMuMSYwJAYDVQQLDB1TdW4gTWljcm9zeXN0\n"118+ "ZW1zIExhYm9yYXRvcmllczEfMB0GA1UEAwwWVGVzdCBDQSAoMTAyNCBiaXQgUlNB\n"119+ "KTAeFw0wOTA0MjcwNDA0MDhaFw0xMzA2MDUwNDA0MDhaMIGgMQswCQYDVQQGEwJV\n"120+ "UzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxHzAdBgNVBAoM\n"121+ "FlN1biBNaWNyb3N5c3RlbXMsIEluYy4xJjAkBgNVBAsMHVN1biBNaWNyb3N5c3Rl\n"122+ "bXMgTGFib3JhdG9yaWVzMSMwIQYDVQQDDBpUZXN0IFNlcnZlciAoMTAyNCBiaXQg\n"123+ "UlNBKTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEArsHHeZ1O67yuxQKDSAOC\n"124+ "Xm271ViwBrXkxe5cvhG8MCCem6Z3XeZ/m6c2ucRwLaQxnmG1m0G6/OYaUXTivjcG\n"125+ "/K4bc1I+yjghAWQNLBtsOiP9w0LKibg3TSDehpeuuz/lmB5A4HMqQr8KkY4K7peD\n"126+ "1QkJ2Dn3zhbwQ/0d8f5CCbkCAwEAATANBgkqhkiG9w0BAQUFAAOBgQBOd8XojEnu\n"127+ "eTUHBwqfmnvRQvbICFDNbbL4KuX/JNPSy1WMGAEbNCTLZ+5yP69js8aUYqAk5vVf\n"128+ "dWRLU3MDiEzW7zxE1ubuKWjVuyGbG8Me0G01Hw+evBcZqB64Fz3OFISVfQh7MqE/\n"129+ "O0AeakRMH350FRLNl4o6KBSXmF/AADfqQQ==\n"130+ "-----END CERTIFICATE-----";131132private static final String SERVER_PRIVATE_KEY133= "-----BEGIN PRIVATE KEY-----\n"134+ "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAK7Bx3mdTuu8rsUC\n"135+ "g0gDgl5tu9VYsAa15MXuXL4RvDAgnpumd13mf5unNrnEcC2kMZ5htZtBuvzmGlF0\n"136+ "4r43BvyuG3NSPso4IQFkDSwbbDoj/cNCyom4N00g3oaXrrs/5ZgeQOBzKkK/CpGO\n"137+ "Cu6Xg9UJCdg5984W8EP9HfH+Qgm5AgMBAAECgYAXUv+3qJo+9mjxHHu/IdDFn6nB\n"138+ "ONwNmTtWe5DfQWi3l7LznU0zOC9x6+hu9NvwC4kf1XSyqxw04tVCZ/JXZurEmEBz\n"139+ "YtcQ5idRQDkKYXEDOeVUfvtHO6xilzrhPKxxd0GG/sei2pozikkqnYF3OcP0qL+a\n"140+ "3nWixZQBRoF2nIRLcQJBAN97TJBr0XTRmE7OCKLUy1+ws7vZB9uQ2efHMsgwOpsY\n"141+ "3cEW5qd95hrxLU72sBeu9loHQgBrT2Q3OAxnsPXmgO0CQQDIL3u9kS/O3Ukx+n1H\n"142+ "JdPFQCRxrDm/vtJpQEmq+mLqxxnxCFRIYQ2ieAPokBxWeMDtdWJGD3VxhahjPfZm\n"143+ "5K59AkEAuDVl0tVMfUIWjT5/F9jXGjUIsZofQ/iN5OLpFOHMLPO+Nd6umPjJpwON\n"144+ "GT11wM/S+DprSPUrJ6vsYy1FTCuHsQJBAMXtnO07xgdE6AAQaRmVnyMiXmY+IQMj\n"145+ "CyuhsrToyDDWFyIoWB0QSMjg3QxuoHYnAqpGK5qV4ksSGgG13BCz/okCQQCRHTgn\n"146+ "DuFG2f7GYLFjI4NaTEzHGp+J9LiNYY1kYYLonpwAC3Z5hzJVanYT3/g23AUZ/fdF\n"147+ "v5PDIViuPo5ZB1eD\n"148+ "-----END PRIVATE KEY-----";149150private static final String CA_PUBLIC_KEY151= "-----BEGIN CERTIFICATE-----\n"152+ "MIIDCDCCAnGgAwIBAgIJAIYlGfwNBY6NMA0GCSqGSIb3DQEBBQUAMIGcMQswCQYD\n"153+ "VQQGEwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxHzAd\n"154+ "BgNVBAoMFlN1biBNaWNyb3N5c3RlbXMsIEluYy4xJjAkBgNVBAsMHVN1biBNaWNy\n"155+ "b3N5c3RlbXMgTGFib3JhdG9yaWVzMR8wHQYDVQQDDBZUZXN0IENBICgxMDI0IGJp\n"156+ "dCBSU0EpMB4XDTA5MDQyNzA0MDQwOFoXDTEzMDYwNTA0MDQwOFowgZwxCzAJBgNV\n"157+ "BAYTAlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEfMB0G\n"158+ "A1UECgwWU3VuIE1pY3Jvc3lzdGVtcywgSW5jLjEmMCQGA1UECwwdU3VuIE1pY3Jv\n"159+ "c3lzdGVtcyBMYWJvcmF0b3JpZXMxHzAdBgNVBAMMFlRlc3QgQ0EgKDEwMjQgYml0\n"160+ "IFJTQSkwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAOK4DJxxb0XX6MJ1CVjp\n"161+ "9Gmr/Ua8MS12R58F9lDpSKuq8cFexA4W7OdZ4jtbKv0tRHX5YxmbnXedwS+gdcOA\n"162+ "GRgXMoeXlgTFGpdL+TR8xKIlMGRSjnR7MpR2tRyIYI2p+UTEiD6LTlIm5Wh4z1q8\n"163+ "LYbxyMVD1XNNNymvPM44OjsBAgMBAAGjUDBOMB0GA1UdDgQWBBT27BLUflmfdtbi\n"164+ "WTgjwWnoxop2MTAfBgNVHSMEGDAWgBT27BLUflmfdtbiWTgjwWnoxop2MTAMBgNV\n"165+ "HRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GBAEQELNzhZpjnSgigd+QJ6I/3CPDo\n"166+ "SDkMLdP1BHlT/DkMIZvABm+M09ePNlWiLYCNCsL9nWmX0gw0rFDKsTklZyKTUzaM\n"167+ "oy/AZCrAaoIc6SO5m1xE1RMyVxd/Y/kg6cbfWxxCJFlMeU5rsSdC97HTE/lDyuoh\n"168+ "BmlOBB7SdR+1ScjA\n"169+ "-----END CERTIFICATE-----";170171private static final String CA_PRIVATE_KEY172= "-----BEGIN PRIVATE KEY-----\n"173+ "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAOK4DJxxb0XX6MJ1\n"174+ "CVjp9Gmr/Ua8MS12R58F9lDpSKuq8cFexA4W7OdZ4jtbKv0tRHX5YxmbnXedwS+g\n"175+ "dcOAGRgXMoeXlgTFGpdL+TR8xKIlMGRSjnR7MpR2tRyIYI2p+UTEiD6LTlIm5Wh4\n"176+ "z1q8LYbxyMVD1XNNNymvPM44OjsBAgMBAAECgYEApmMOlk3FrQtsvjGof4GLp3Xa\n"177+ "tmvs54FzxKhagj0C4UHelNyYpAJ9MLjNiGQ7I31yTeaNrUCAi0XSfsKTSrwbLSnJ\n"178+ "qsUPKMBrnzcWrOyui2+cupHZXaTlNeYB97teLJYpa6Ql9CZLoTHoim1+//s7diBh\n"179+ "03Vls+M6Poi5PMvv59UCQQD+k/BiokmbBgWHfBY5cZSlx3Z4VTwSHJmHDTO3Tjso\n"180+ "EVErXUSVvqD/KHX6eM4VPM8lySV5djWV8lDsESCWMtiLAkEA4/xFNsiOLMQpxW/O\n"181+ "bt2tukxJkAxldD4lPoFZR+zbXtMtt8OjERtX2wD+nj6h7jfIeSyVuBEcBN8Uj8xe\n"182+ "kgfgIwJAPbKG4LCqHAsCjgpRrIxNVTwZByLJEy6hOqzFathn19cSj+rjs1Lm28/n\n"183+ "f9OFRnpdTbAJB/3REM0QNZYVCrG57wJBAN0KuTytZJNouaswhPCew5Kt5mDgc/kp\n"184+ "S8j3dk2zCto8W8Ygy1iJrzuqEjPxO+UQdrFtlde51vWuKGxnVIW3VwsCQEldqk7r\n"185+ "8y7PgquPP+k3L0OXno5wGBrPcW1+U0mhIZGnwSzE4SPX2ddqUSEUA/Av4RjAckL/\n"186+ "fpqmCkpTanyYW9U=\n"187+ "-----END PRIVATE KEY-----";188189private final SSLSocketFactory factory;190private final X509ExtendedKeyManager clientKeyManager;191private final X509ExtendedKeyManager serverKeyManager;192private final X509TrustManager clientTrustManager;193private final X509TrustManager serverTrustManager;194195static abstract class Server implements Runnable, AutoCloseable {196197final CipherTestUtils cipherTest;198199Server(CipherTestUtils cipherTest) throws Exception {200this.cipherTest = cipherTest;201}202203@Override204public abstract void run();205206abstract int getPort();207208void handleRequest(InputStream in, OutputStream out)209throws IOException {210boolean newline = false;211StringBuilder sb = new StringBuilder();212while (true) {213int ch = in.read();214if (ch < 0) {215throw new EOFException();216}217sb.append((char) ch);218if (ch == '\r') {219// empty220} else if (ch == '\n') {221if (newline) {222// 2nd newline in a row, end of request223break;224}225newline = true;226} else {227newline = false;228}229}230String request = sb.toString();231if (request.startsWith("GET / HTTP/1.") == false) {232throw new IOException("Invalid request: " + request);233}234out.write("HTTP/1.0 200 OK\r\n\r\n".getBytes());235out.write("Tested Scenario: ".getBytes());236TestParameters tp = (TestParameters) CipherTestUtils.TESTS.get(0);237out.write(tp.toString().getBytes());238out.write(" Test PASSED.".getBytes());239}240}241242public static class TestParameters {243244final String cipherSuite;245final String protocol;246final String clientAuth;247248TestParameters(String cipherSuite, String protocol, String clientAuth) {249this.cipherSuite = cipherSuite;250this.protocol = protocol;251this.clientAuth = clientAuth;252}253254boolean isEnabled() {255return true;256}257258@Override259public String toString() {260String s = cipherSuite + " in " + protocol + " mode";261if (clientAuth != null) {262s += " with " + clientAuth + " client authentication";263}264return s;265}266}267268private static volatile CipherTestUtils instance = null;269270public static CipherTestUtils getInstance() throws Exception {271if (instance == null) {272synchronized (CipherTestUtils.class) {273if (instance == null) {274instance = new CipherTestUtils();275}276}277}278return instance;279}280281public static void setTestedArguments(String protocol, String ciphersuite) {282ciphersuite = ciphersuite.trim();283TestParameters params = new TestParameters(ciphersuite, protocol, null);284TESTS.add(params);285}286287public X509ExtendedKeyManager getClientKeyManager() {288return clientKeyManager;289}290291public X509TrustManager getClientTrustManager() {292return clientTrustManager;293}294295public X509ExtendedKeyManager getServerKeyManager() {296return serverKeyManager;297}298299public X509TrustManager getServerTrustManager() {300return serverTrustManager;301}302303public static void addFailure(Exception e) {304EXCEPTIONS.add(e);305}306307private CipherTestUtils() throws Exception {308factory = (SSLSocketFactory) SSLSocketFactory.getDefault();309KeyStore serverKeyStore = createServerKeyStore(SERVER_PUBLIC_KEY,310SERVER_PRIVATE_KEY);311KeyStore serverTrustStore = createServerKeyStore(CA_PUBLIC_KEY,312CA_PRIVATE_KEY);313314if (serverKeyStore != null) {315KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(316KeyManagerFactory.getDefaultAlgorithm());317keyFactory.init(serverKeyStore, PASSWORD);318serverKeyManager = (X509ExtendedKeyManager)319keyFactory.getKeyManagers()[0];320} else {321serverKeyManager = null;322}323serverTrustManager = serverTrustStore != null324? new AlwaysTrustManager(serverTrustStore) : null;325326KeyStore clientKeyStore, clientTrustStore;327clientTrustStore = serverTrustStore;328clientKeyStore =329createServerKeyStore(CLIENT_PUBLIC_KEY,CLIENT_PRIVATE_KEY);330if (clientKeyStore != null) {331KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(332KeyManagerFactory.getDefaultAlgorithm());333keyFactory.init(clientKeyStore, PASSWORD);334clientKeyManager = (X509ExtendedKeyManager)335keyFactory.getKeyManagers()[0];336} else {337clientKeyManager = null;338}339clientTrustManager = (clientTrustStore != null)340? new AlwaysTrustManager(clientTrustStore) : null;341}342343void checkResult(String exception) throws Exception {344if (EXCEPTIONS.size() >= 1) {345Exception actualException = EXCEPTIONS.get(0);346if (exception == null) {347throw new RuntimeException("FAILED: got unexpected exception: "348+ actualException);349}350if (!exception.equals(actualException.getClass().getName())) {351throw new RuntimeException("FAILED: got unexpected exception: "352+ actualException);353}354355System.out.println("PASSED: got expected exception: "356+ actualException);357} else {358if (exception != null) {359throw new RuntimeException("FAILED: " + exception360+ " was expected");361}362System.out.println("PASSED");363}364}365366SSLSocketFactory getFactory() {367return factory;368}369370static abstract class Client implements Runnable {371372final CipherTestUtils cipherTest;373TestParameters testedParams;374375Client(CipherTestUtils cipherTest) throws Exception {376this.cipherTest = cipherTest;377}378379Client(CipherTestUtils cipherTest, String testedCipherSuite)380throws Exception {381this.cipherTest = cipherTest;382}383384@Override385public final void run() {386387TESTS.stream().map((params) -> {388if (!params.isEnabled()) {389System.out.println("Skipping disabled test " + params);390}391return params;392}).forEach((params) -> {393try {394System.out.println("Testing " + params);395runTest(params);396System.out.println("Passed " + params);397} catch (Exception e) {398CipherTestUtils.addFailure(e);399System.out.println("** Failed " + params400+ "**, got exception:");401e.printStackTrace(System.out);402}403});404}405406abstract void runTest(TestParameters params) throws Exception;407408void sendRequest(InputStream in, OutputStream out) throws IOException {409out.write("GET / HTTP/1.0\r\n\r\n".getBytes());410out.flush();411StringBuilder sb = new StringBuilder();412while (true) {413int ch = in.read();414if (ch < 0) {415break;416}417sb.append((char) ch);418}419String response = sb.toString();420if (response.startsWith("HTTP/1.0 200 ") == false) {421throw new IOException("Invalid response: " + response);422} else {423System.out.println();424System.out.println("--- Response --- ");425System.out.println(response);426System.out.println("---------------- ");427}428}429}430431public static void printStringArray(String[] stringArray) {432System.out.println(Arrays.toString(stringArray));433System.out.println();434}435436public static void printInfo(SSLServerSocket socket) {437System.out.println();438System.out.println("--- SSL ServerSocket Info ---");439System.out.print("SupportedProtocols : ");440printStringArray(socket.getSupportedProtocols());441System.out.print("SupportedCipherSuites : ");442printStringArray(socket.getSupportedCipherSuites());443System.out.print("EnabledProtocols : ");444printStringArray(socket.getEnabledProtocols());445System.out.print("EnabledCipherSuites : ");446String[] supportedCipherSuites = socket.getEnabledCipherSuites();447Arrays.sort(supportedCipherSuites);448printStringArray(supportedCipherSuites);449System.out.println("NeedClientAuth : "450+ socket.getNeedClientAuth());451System.out.println("WantClientAuth : "452+ socket.getWantClientAuth());453System.out.println("-----------------------");454}455456public static void printInfo(SSLSocket socket) {457System.out.println();458System.out.println("--- SSL Socket Info ---");459System.out.print(" SupportedProtocols : ");460printStringArray(socket.getSupportedProtocols());461System.out.println(" EnabledProtocols : "462+ socket.getEnabledProtocols()[0]);463System.out.print(" SupportedCipherSuites : ");464String[] supportedCipherSuites = socket.getEnabledCipherSuites();465Arrays.sort(supportedCipherSuites);466printStringArray(supportedCipherSuites);467System.out.println(" EnabledCipherSuites : "468+ socket.getEnabledCipherSuites()[0]);469System.out.println(" NeedClientAuth : "470+ socket.getNeedClientAuth());471System.out.println(" WantClientAuth : "472+ socket.getWantClientAuth());473System.out.println("-----------------------");474}475476private static KeyStore createServerKeyStore(String publicKey,477String keySpecStr) throws KeyStoreException, IOException,478NoSuchAlgorithmException, CertificateException,479InvalidKeySpecException {480481KeyStore ks = KeyStore.getInstance("JKS");482ks.load(null, null);483if (publicKey == null || keySpecStr == null) {484throw new IllegalArgumentException("publicKey or "485+ "keySpecStr cannot be null");486}487String strippedPrivateKey = keySpecStr.substring(488keySpecStr.indexOf("\n"), keySpecStr.lastIndexOf("\n"));489490// generate the private key.491PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(492Base64.getMimeDecoder().decode(strippedPrivateKey));493KeyFactory kf = KeyFactory.getInstance("RSA");494RSAPrivateKey priKey495= (RSAPrivateKey) kf.generatePrivate(priKeySpec);496497// generate certificate chain498try (InputStream is = new ByteArrayInputStream(publicKey.getBytes())) {499// generate certificate from cert string500CertificateFactory cf = CertificateFactory.getInstance("X.509");501Certificate keyCert = cf.generateCertificate(is);502Certificate[] chain = {keyCert};503ks.setKeyEntry("TestEntry", priKey, PASSWORD, chain);504}505506return ks;507}508509public static Server mainServer(PeerFactory peerFactory,510String expectedException) throws Exception {511512setTestedArguments(peerFactory.getTestedProtocol(),513peerFactory.getTestedCipher());514515System.out.print(516" Initializing test '" + peerFactory.getName() + "'...");517secureRandom.nextInt();518519CipherTestUtils cipherTest = CipherTestUtils.getInstance();520Server srv = peerFactory.newServer(cipherTest, PeerFactory.FREE_PORT);521Thread serverThread = new Thread(srv, "Server");522serverThread.start();523524return srv;525}526527public static void mainClient(PeerFactory peerFactory, int port,528String expectedException) throws Exception {529530long time = System.currentTimeMillis();531setTestedArguments(peerFactory.getTestedProtocol(),532peerFactory.getTestedCipher());533534System.out.print(535" Initializing test '" + peerFactory.getName() + "'...");536secureRandom.nextInt();537538CipherTestUtils cipherTest = CipherTestUtils.getInstance();539peerFactory.newClient(cipherTest, port).run();540cipherTest.checkResult(expectedException);541542time = System.currentTimeMillis() - time;543System.out.println("Elapsed time " + time);544}545546public static abstract class PeerFactory {547548public static final int FREE_PORT = 0;549550abstract String getName();551552abstract String getTestedProtocol();553554abstract String getTestedCipher();555556abstract Client newClient(CipherTestUtils cipherTest, int testPort)557throws Exception;558559abstract Server newServer(CipherTestUtils cipherTest, int testPort)560throws Exception;561562boolean isSupported(String cipherSuite) {563return true;564}565}566}567568class AlwaysTrustManager implements X509TrustManager {569570X509TrustManager trustManager;571572public AlwaysTrustManager(KeyStore keyStore)573throws NoSuchAlgorithmException, KeyStoreException {574575TrustManagerFactory tmf576= TrustManagerFactory.getInstance(TrustManagerFactory.577getDefaultAlgorithm());578tmf.init(keyStore);579580TrustManager tms[] = tmf.getTrustManagers();581for (TrustManager tm : tms) {582trustManager = (X509TrustManager) tm;583return;584}585586}587588@Override589public void checkClientTrusted(X509Certificate[] chain, String authType)590throws CertificateException {591try {592trustManager.checkClientTrusted(chain, authType);593} catch (CertificateException excep) {594System.out.println("ERROR in client trust manager: " + excep);595}596}597598@Override599public void checkServerTrusted(X509Certificate[] chain, String authType)600throws CertificateException {601try {602trustManager.checkServerTrusted(chain, authType);603} catch (CertificateException excep) {604System.out.println("ERROR in server trust manager: " + excep);605}606}607608@Override609public X509Certificate[] getAcceptedIssuers() {610return trustManager.getAcceptedIssuers();611}612}613614class MyX509KeyManager extends X509ExtendedKeyManager {615616private final X509ExtendedKeyManager keyManager;617private String authType;618619MyX509KeyManager(X509ExtendedKeyManager keyManager) {620this.keyManager = keyManager;621}622623void setAuthType(String authType) {624this.authType = "ECDSA".equals(authType) ? "EC" : authType;625}626627@Override628public String[] getClientAliases(String keyType, Principal[] issuers) {629if (authType == null) {630return null;631}632return keyManager.getClientAliases(authType, issuers);633}634635@Override636public String chooseClientAlias(String[] keyType, Principal[] issuers,637Socket socket) {638if (authType == null) {639return null;640}641return keyManager.chooseClientAlias(new String[]{authType},642issuers, socket);643}644645@Override646public String chooseEngineClientAlias(String[] keyType,647Principal[] issuers, SSLEngine engine) {648if (authType == null) {649return null;650}651return keyManager.chooseEngineClientAlias(new String[]{authType},652issuers, engine);653}654655@Override656public String[] getServerAliases(String keyType, Principal[] issuers) {657throw new UnsupportedOperationException("Servers not supported");658}659660@Override661public String chooseServerAlias(String keyType, Principal[] issuers,662Socket socket) {663throw new UnsupportedOperationException("Servers not supported");664}665666@Override667public String chooseEngineServerAlias(String keyType, Principal[] issuers,668SSLEngine engine) {669throw new UnsupportedOperationException("Servers not supported");670}671672@Override673public X509Certificate[] getCertificateChain(String alias) {674return keyManager.getCertificateChain(alias);675}676677@Override678public PrivateKey getPrivateKey(String alias) {679return keyManager.getPrivateKey(alias);680}681}682683684