summaryrefslogtreecommitdiffstats
path: root/luni/src/test/java/tests/api/javax/net/ssl/SSLSocketTest.java
blob: ab60f72335e3210d71d3d2fa70cc11727e3528ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package tests.api.javax.net.ssl;

import dalvik.annotation.AndroidOnly;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.Arrays;
import javax.net.ssl.HandshakeCompletedEvent;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.security.cert.X509Certificate;
import junit.framework.TestCase;
import libcore.io.Base64;
import tests.api.javax.net.ssl.HandshakeCompletedEventTest.TestTrustManager;
import tests.support.Support_PortManager;
import libcore.java.security.StandardNames;

public class SSLSocketTest extends TestCase {

    public class HandshakeCL implements HandshakeCompletedListener {
        public void handshakeCompleted(HandshakeCompletedEvent event) {
        }
    }

    /**
     * javax.net.ssl.SSLSocket#SSLSocket()
     */
    public void testConstructor_01() throws Exception {
        SSLSocket ssl = getSSLSocket();
        assertNotNull(ssl);
        ssl.close();
    }

    /**
     * javax.net.ssl.SSLSocket#SSLSocket(InetAddress address, int port)
     */
    public void testConstructor_02() throws UnknownHostException, IOException {
        int sport = startServer("Cons InetAddress,I");
        int[] invalidPort = {-1, Integer.MIN_VALUE, 65536, Integer.MAX_VALUE};

        SSLSocket ssl = getSSLSocket(InetAddress.getLocalHost(), sport);
        assertNotNull(ssl);
        assertEquals(sport, ssl.getPort());
        ssl.close();

        try {
            getSSLSocket(InetAddress.getLocalHost(), sport + 1);
            fail();
        } catch (IOException expected) {
        }

        for (int i = 0; i < invalidPort.length; i++) {
            try {
                getSSLSocket(InetAddress.getLocalHost(), invalidPort[i]);
                fail();
            } catch (IllegalArgumentException expected) {
            }
        }
    }

    /**
     * javax.net.ssl.SSLSocket#SSLSocket(InetAddress address, int port,
     *                                          InetAddress clientAddress, int clientPort)
     */
    public void testConstructor_03() throws UnknownHostException, IOException {
        int sport = startServer("Cons InetAddress,I,InetAddress,I");
        int portNumber = Support_PortManager.getNextPort();

        SSLSocket ssl = getSSLSocket(InetAddress.getLocalHost(), sport,
                                     InetAddress.getLocalHost(), portNumber);
        assertNotNull(ssl);
        assertEquals(sport, ssl.getPort());
        assertEquals(portNumber, ssl.getLocalPort());
        ssl.close();

        try {
            getSSLSocket(InetAddress.getLocalHost(), 8081, InetAddress.getLocalHost(), 8082);
            fail();
        } catch (IOException expected) {
        }

        try {
            getSSLSocket(InetAddress.getLocalHost(), -1, InetAddress.getLocalHost(), sport + 1);
            fail();
        } catch (IllegalArgumentException expected) {
        }
        try {
            getSSLSocket(InetAddress.getLocalHost(), sport, InetAddress.getLocalHost(), -1);
            fail();
        } catch (IllegalArgumentException expected) {
        }

        try {
            getSSLSocket(InetAddress.getLocalHost(), Integer.MIN_VALUE,
                         InetAddress.getLocalHost(), sport + 1);
            fail();
        } catch (IOException expectedOnRI) {
            assertTrue(StandardNames.IS_RI);
        } catch (IllegalArgumentException expectedOnAndroid) {
            assertFalse(StandardNames.IS_RI);
        }
        try {
            getSSLSocket(InetAddress.getLocalHost(), sport,
                         InetAddress.getLocalHost(), Integer.MAX_VALUE);
            fail();
        } catch (IllegalArgumentException expectedOnAndroid) {
            assertFalse(StandardNames.IS_RI);
        }
    }

    /**
     * javax.net.ssl.SSLSocket#SSLSocket(String host, int port)
     */
    public void testConstructor_04() throws UnknownHostException, IOException {
        int sport = startServer("Cons String,I");
        int[] invalidPort = {-1, Integer.MIN_VALUE, 65536, Integer.MAX_VALUE};

        SSLSocket ssl = getSSLSocket(InetAddress.getLocalHost().getHostName(), sport);
        assertNotNull(ssl);
        assertEquals(sport, ssl.getPort());
        ssl.close();

        try {
            getSSLSocket("localhost", 8082);
            fail();
        } catch (IOException expected) {
        }

        for (int i = 0; i < invalidPort.length; i++) {
            try {
                getSSLSocket(InetAddress.getLocalHost().getHostName(), invalidPort[i]);
                fail();
            } catch (IllegalArgumentException expected) {
            }
        }

        try {
            getSSLSocket("bla-bla", sport);
            fail();
        } catch (UnknownHostException expected) {
        }
    }

    /**
     * javax.net.ssl.SSLSocket#SSLSocket(String host, int port, InetAddress clientAddress,
     *           int clientPort)
     */
    public void testConstructor_05() throws UnknownHostException, IOException {
        int sport = startServer("Cons String,I,InetAddress,I");
        int portNumber = Support_PortManager.getNextPort();
        int[] invalidPort = {-1, Integer.MIN_VALUE, 65536, Integer.MAX_VALUE};

        SSLSocket ssl = getSSLSocket(InetAddress.getLocalHost().getHostName(), sport,
                                     InetAddress.getLocalHost(), portNumber);
        assertNotNull(ssl);
        assertEquals(sport, ssl.getPort());
        assertEquals(portNumber, ssl.getLocalPort());

        try {
            getSSLSocket("localhost", 8081, InetAddress.getLocalHost(), 8082);
            fail();
        } catch (IOException expected) {
        }

        for (int i = 0; i < invalidPort.length; i++) {
            portNumber = Support_PortManager.getNextPort();
            try {
                getSSLSocket(InetAddress.getLocalHost().getHostName(), invalidPort[i],
                             InetAddress.getLocalHost(), portNumber);
                fail();
            } catch (IllegalArgumentException expected) {
            }
            try {
                getSSLSocket(InetAddress.getLocalHost().getHostName(), sport,
                             InetAddress.getLocalHost(), invalidPort[i]);
                fail();
            } catch (IllegalArgumentException expected) {
            }
        }

        portNumber = Support_PortManager.getNextPort();
        try {
            getSSLSocket("bla-bla", sport, InetAddress.getLocalHost(), portNumber);
            fail();
        } catch (UnknownHostException expected) {
        }
    }

    public void test_creationStressTest() throws Exception {
        // Test the default codepath, which uses /dev/urandom.
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, null, null);
        for (int i = 0; i < 2048; ++i) {
            sslContext.getSocketFactory().createSocket().close();
        }

        // Test the other codepath, which copies a seed from a byte[].
        sslContext.init(null, null, new SecureRandom());
        for (int i = 0; i < 2048; ++i) {
            sslContext.getSocketFactory().createSocket().close();
        }
    }

    /**
     * javax.net.ssl.SSLSocket#addHandshakeCompletedListener(HandshakeCompletedListener listener)
     */
    @AndroidOnly("RI doesn't throw the specified IAE")
    public void test_addHandshakeCompletedListener() throws IOException {
        SSLSocket ssl = getSSLSocket();
        HandshakeCompletedListener ls = new HandshakeCL();
        try {
            ssl.addHandshakeCompletedListener(null);
            fail();
        } catch (IllegalArgumentException expected) {
        }
        ssl.addHandshakeCompletedListener(ls);
        ssl.close();
    }

    /**
     * javax.net.ssl.SSLSocket#removeHandshakeCompletedListener(HandshakeCompletedListener listener)
     */
    public void test_removeHandshakeCompletedListener() throws IOException {
        SSLSocket ssl = getSSLSocket();
        HandshakeCompletedListener ls = new HandshakeCL();
        try {
            ssl.removeHandshakeCompletedListener(null);
            fail();
        } catch (IllegalArgumentException expected) {
        }

        try {
            ssl.removeHandshakeCompletedListener(ls);
        } catch (IllegalArgumentException expected) {
        }

        ssl.addHandshakeCompletedListener(ls);
        ssl.removeHandshakeCompletedListener(ls);
        ssl.close();
    }

    /**
     * javax.net.ssl.SSLSocket#setEnableSessionCreation(boolean flag)
     * javax.net.ssl.SSLSocket#getEnableSessionCreation()
     */
    public void test_EnableSessionCreation() throws IOException {
        SSLSocket ssl = getSSLSocket();
        assertTrue(ssl.getEnableSessionCreation());
        ssl.setEnableSessionCreation(false);
        assertFalse(ssl.getEnableSessionCreation());
        ssl.setEnableSessionCreation(true);
        assertTrue(ssl.getEnableSessionCreation());
        ssl.close();
    }

    /**
     * javax.net.ssl.SSLSocket#setNeedClientAuth(boolean need)
     * javax.net.ssl.SSLSocket#getNeedClientAuthCreation()
     */
    public void test_NeedClientAuth() throws UnknownHostException, IOException {
        SSLSocket ssl = getSSLSocket();
        ssl.setNeedClientAuth(true);
        assertTrue(ssl.getNeedClientAuth());
        ssl.setNeedClientAuth(false);
        assertFalse(ssl.getNeedClientAuth());
        ssl.close();
    }

    /**
     * javax.net.ssl.SSLSocket#setWantClientAuth(boolean want)
     * javax.net.ssl.SSLSocket#getWantClientAuthCreation()
     */
    public void test_WantClientAuth() throws UnknownHostException, IOException {
        SSLSocket ssl = getSSLSocket();
        ssl.setWantClientAuth(true);
        assertTrue(ssl.getWantClientAuth());
        ssl.setWantClientAuth(false);
        assertFalse(ssl.getWantClientAuth());
        ssl.close();
    }

    /**
     * javax.net.ssl.SSLSocket#getSupportedProtocols()
     */
    public void test_getSupportedProtocols() throws IOException {
        SSLSocket ssl = getSSLSocket();
        String[] res = ssl.getSupportedProtocols();
        assertTrue("No supported protocols found", res.length > 0);
        ssl.close();
    }

    /**
     * javax.net.ssl.SSLSocket#getEnabledProtocols()
     * javax.net.ssl.SSLSocket#setEnabledProtocols(String[] protocols)
     */
    public void test_EnabledProtocols() throws IOException {
        SSLSocket ssl = getSSLSocket();
        try {
            ssl.setEnabledProtocols(null);
            fail();
        } catch (IllegalArgumentException expected) {
        }
        ssl.setEnabledProtocols(new String[] {});
        try {
            ssl.setEnabledProtocols(new String[] {"blubb"});
            fail();
        } catch (IllegalArgumentException expected) {
        }
        ssl.setEnabledProtocols(ssl.getEnabledProtocols());
        String[] res = ssl.getEnabledProtocols();
        assertEquals("no enabled protocols set",
                     ssl.getEnabledProtocols().length, res.length);
        ssl.close();
    }

    /**
     * javax.net.ssl.SSLSocket#getSession()
     */
    public void test_getSession() throws IOException {
        SSLSocket ssl = getSSLSocket();
        assertNotNull(ssl.getSession());
        ssl.close();
    }

    /**
     * javax.net.ssl.SSLSocket#getSupportedCipherSuites()
     */
    public void test_getSupportedCipherSuites() throws IOException {
        SSLSocket ssl = getSSLSocket();
        String[] res = ssl.getSupportedCipherSuites();
        assertTrue("no supported cipher suites", res.length > 0);
        ssl.close();
    }

    /**
     * javax.net.ssl.SSLSocket#getEnabledCipherSuites()
     * javax.net.ssl.SSLSocket#setEnabledCipherSuites(String[] suites)
     */
    public void test_EnabledCipherSuites() throws IOException {
        SSLSocket ssl = getSSLSocket();
        try {
            ssl.setEnabledCipherSuites(null);
            fail();
        } catch (IllegalArgumentException expected) {
        }
        ssl.setEnabledCipherSuites(new String[] {});
        try {
            ssl.setEnabledCipherSuites(new String[] {"blubb"});
            fail();
        } catch (IllegalArgumentException expected) {
        }
        ssl.setEnabledCipherSuites(ssl.getSupportedCipherSuites());
        String[] res = ssl.getEnabledCipherSuites();
        assertNotNull("NULL result", res);
        assertEquals("not all supported cipher suites were enabled",
                     Arrays.asList(ssl.getSupportedCipherSuites()),
                     Arrays.asList(res));
        ssl.close();
    }

    /**
     * javax.net.ssl.SSLSocket#getUseClientMode()
     * javax.net.ssl.SSLSocket#setUseClientMode(boolean mode)
     */
    public void test_UseClientMode() throws IOException {
        SSLSocket ssl = getSSLSocket();
        assertTrue(ssl.getUseClientMode());
        ssl.setUseClientMode(false);
        assertFalse(ssl.getUseClientMode());
        ssl.close();

        ssl = getSSLSocket("localhost", startServer("UseClientMode"));
        try {
            ssl.startHandshake();
        } catch (IOException ioe) {
            //fail(ioe + " was thrown for method startHandshake()");
        }
        try {
            ssl.setUseClientMode(false);
            fail();
        } catch (IllegalArgumentException expected) {
        }
        ssl.close();
    }

    /**
     * javax.net.ssl.SSLSocket#startHandshake()
     */
    public void test_startHandshake() throws IOException {
        SSLSocket ssl = getSSLSocket();
        try {
            ssl.startHandshake();
            fail();
        } catch (IOException expected) {
        }
        ssl.close();
    }

    boolean useBKS = !StandardNames.IS_RI;

    private String PASSWORD = "android";

    private int port = Support_PortManager.getNextPort();

    private boolean serverReady = false;

    /**
     * Defines the keystore contents for the server, BKS version. Holds just a
     * single self-generated key. The subject name is "Test Server".
     */
    private static final String SERVER_KEYS_BKS = ""
            + "AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41"
            + "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET"
            + "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV"
            + "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw"
            + "MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U"
            + "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl"
            + "cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy"
            + "DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV"
            + "zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG"
            + "9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU"
            + "hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV"
            + "yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx"
            + "4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR"
            + "MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN"
            + "vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs"
            + "P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck"
            + "MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM"
            + "J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI"
            + "rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f"
            + "V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx"
            + "OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt"
            + "bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw"
            + "1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl"
            + "k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw=";

    /**
     * Defines the keystore contents for the server, JKS version. Holds just a
     * single self-generated key. The subject name is "Test Server".
     */
    private static final String SERVER_KEYS_JKS = ""
            + "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFfBeAAAArowggK2MA4GCisGAQQBKgIRAQEFAASC"
            + "AqI2kp5XjnF8YZkhcF92YsJNQkvsmH7zqMM87j23zSoV4DwyE3XeC/gZWq1ToScIhoqZkzlbWcu4"
            + "T/Zfc/DrfGk/rKbBL1uWKGZ8fMtlZk8KoAhxZk1JSyJvdkyKxqmzUbxk1OFMlN2VJNu97FPVH+du"
            + "dvjTvmpdoM81INWBW/1fZJeQeDvn4mMbbe0IxgpiLnI9WSevlaDP/sm1X3iO9yEyzHLL+M5Erspo"
            + "Cwa558fOu5DdsICMXhvDQxjWFKFhPHnKtGe+VvwkG9/bAaDgx3kfhk0w5zvdnkKb+8Ed9ylNRzdk"
            + "ocAa/mxlMTOsTvDKXjjsBupNPIIj7OP4GNnZaxkJjSs98pEO67op1GX2qhy6FSOPNuq8k/65HzUc"
            + "PYn6voEeh6vm02U/sjEnzRevQ2+2wXoAdp0EwtQ/DlMe+NvcwPGWKuMgX4A4L93DZGb04N2VmAU3"
            + "YLOtZwTO0LbuWrcCM/q99G/7LcczkxIVrO2I/rh8RXVczlf9QzcrFObFv4ATuspWJ8xG7DhsMbnk"
            + "rT94Pq6TogYeoz8o8ZMykesAqN6mt/9+ToIemmXv+e+KU1hI5oLwWMnUG6dXM6hIvrULY6o+QCPH"
            + "172YQJMa+68HAeS+itBTAF4Clm/bLn6reHCGGU6vNdwU0lYldpiOj9cB3t+u2UuLo6tiFWjLf5Zs"
            + "EQJETd4g/EK9nHxJn0GAKrWnTw7pEHQJ08elzUuy04C/jEEG+4QXU1InzS4o/kR0Sqz2WTGDoSoq"
            + "ewuPRU5bzQs/b9daq3mXrnPtRBL6HfSDAdpTK76iHqLCGdqx3avHjVSBm4zFvEuYBCev+3iKOBmg"
            + "yh7eQRTjz4UOWfy85omMBr7lK8PtfVBDzOXpasxS0uBgdUyBDX4tO6k9jZ8a1kmQRQAAAAEABVgu"
            + "NTA5AAACSDCCAkQwggGtAgRIR8SKMA0GCSqGSIb3DQEBBAUAMGkxCzAJBgNVBAYTAlVTMRMwEQYD"
            + "VQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzANBgNVBAoTBkdvb2dsZTEQMA4GA1UECxMH"
            + "QW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBTZXJ2ZXIwHhcNMDgwNjA1MTA0ODQyWhcNMDgwOTAzMTA0"
            + "ODQyWjBpMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8w"
            + "DQYDVQQKEwZHb29nbGUxEDAOBgNVBAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMIGf"
            + "MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwoC6chqCI84rj1PrXuJgbiit4EV909zR6N0jNlYfg"
            + "itwB39bP39wH03rFm8T59b3mbSptnGmCIpLZn25KPPFsYD3JJ+wFlmiUdEP9H05flfwtFQJnw9uT"
            + "3rRIdYVMPcQ3RoZzwAMliGr882I2thIDbA6xjGU/1nRIdvk0LtxH3QIDAQABMA0GCSqGSIb3DQEB"
            + "BAUAA4GBAJn+6YgUlY18Ie+0+Vt8oEi81DNi/bfPrAUAh63fhhBikx/3R9dl3wh09Z6p7cIdNxjW"
            + "n2ll+cRW9eqF7z75F0Omm0C7/KAEPjukVbszmzeU5VqzkpSt0j84YWi+TfcHRrfvhLbrlmGITVpY"
            + "ol5pHLDyqGmDs53pgwipWqsn/nEXEBgj3EoqPeqHbDf7YaP8h/5BSt0=";

    protected int startServer(String name) {
        String keys = useBKS ? SERVER_KEYS_BKS : SERVER_KEYS_JKS;
        TestServer server = new TestServer(true, keys);
        Thread serverThread = new Thread(server);
        serverThread.start();
        try {
            while (!serverReady) {
                Exception e = server.getException();
                if (e != null) {
                    throw new AssertionError(e);
                }
                Thread.currentThread().sleep(50);
            }
            // give the server 100 millis to accept
            Thread.currentThread().sleep(100);
        } catch (InterruptedException ignore) {
        }
        return server.sport;
    }

    /**
     * Implements a test SSL socket server. It wait for a connection on a given
     * port, requests client authentication (if specified), and read 256 bytes
     * from the socket.
     */
    class TestServer implements Runnable {

        public static final int CLIENT_AUTH_NONE = 0;

        public static final int CLIENT_AUTH_WANTED = 1;

        public static final int CLIENT_AUTH_NEEDED = 2;

        private TestTrustManager trustManager;

        private Exception exception;

        String keys;

        private boolean provideKeys;

        int sport;

        public TestServer(boolean provideKeys, String keys) {
            this.keys = keys;
            this.provideKeys = provideKeys;

            trustManager = new TestTrustManager();
        }

        public void run() {
            try {
                KeyManager[] keyManagers = provideKeys ? getKeyManagers(keys) : null;
                TrustManager[] trustManagers = new TrustManager[] { trustManager };

                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(keyManagers, trustManagers, null);

                SSLServerSocket serverSocket = (SSLServerSocket)
                        sslContext.getServerSocketFactory().createServerSocket();
                try {
                    serverSocket.bind(new InetSocketAddress(port));
                    sport = serverSocket.getLocalPort();
                    serverReady = true;

                    SSLSocket clientSocket = (SSLSocket)serverSocket.accept();

                    try {
                        InputStream stream = clientSocket.getInputStream();
                        try {
                            for (int i = 0; i < 256; i++) {
                                int j = stream.read();
                                if (i != j) {
                                    throw new RuntimeException("Error reading socket, expected " + i
                                                               + ", got " + j);
                                }
                            }
                        } finally {
                            stream.close();
                        }
                    } finally {
                        clientSocket.close();
                    }
                } finally {
                    serverSocket.close();
                }
            } catch (Exception ex) {
                exception = ex;
            }
        }

        public Exception getException() {
            return exception;
        }

        public X509Certificate[] getChain() {
            return trustManager.getChain();
        }

    }

    /**
     * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
     * for the result.
     */
    private KeyManager[] getKeyManagers(String keys) throws Exception {
        byte[] bytes = Base64.decode(keys.getBytes());
        InputStream inputStream = new ByteArrayInputStream(bytes);

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(inputStream, PASSWORD.toCharArray());
        inputStream.close();

        String algorithm = KeyManagerFactory.getDefaultAlgorithm();
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
        keyManagerFactory.init(keyStore, PASSWORD.toCharArray());

        return keyManagerFactory.getKeyManagers();
    }

    private SSLSocket getSSLSocket() throws IOException {
        return (SSLSocket) SSLSocketFactory.getDefault().createSocket();
    }

    private SSLSocket getSSLSocket(InetAddress host, int port) throws IOException {
        return (SSLSocket) SSLSocketFactory.getDefault().createSocket(host, port);
    }

    private SSLSocket getSSLSocket(String host, int port) throws UnknownHostException, IOException {
        return (SSLSocket) SSLSocketFactory.getDefault().createSocket(host, port);
    }

    private SSLSocket getSSLSocket(InetAddress host, int port, InetAddress localHost, int localPort)
            throws IOException {
        return (SSLSocket) SSLSocketFactory.getDefault().createSocket(host,
                                                                      port,
                                                                      localHost,
                                                                      localPort);
    }

    private SSLSocket getSSLSocket(String host, int port, InetAddress localHost, int localPort)
            throws UnknownHostException, IOException {
        return (SSLSocket) SSLSocketFactory.getDefault().createSocket(host,
                                                                      port,
                                                                      localHost,
                                                                      localPort);
    }
}