1 /*
   2  * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 //
  25 // SunJSSE does not support dynamic system properties, no way to re-use
  26 // system properties in samevm/agentvm mode.
  27 //
  28 
  29 /*
  30  * @test
  31  * @bug 6956398
  32  * @summary make ephemeral DH key match the length of the certificate key
  33  * @run main/othervm
  34  *      DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA true 1318 75
  35  * @run main/othervm -Djdk.tls.ephemeralDHKeySize=matched
  36  *      DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA true 1318 75
  37  * @run main/othervm -Djdk.tls.ephemeralDHKeySize=legacy
  38  *      DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA true 1318 75
  39  * @run main/othervm -Djdk.tls.ephemeralDHKeySize=1024
  40  *      DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA true 1318 75
  41  *
  42  * @run main/othervm
  43  *      DHEKeySizing SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA true 292 75
  44  *
  45  * @run main/othervm
  46  *      DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA  false 1510 139
  47  * @run main/othervm -Djdk.tls.ephemeralDHKeySize=legacy
  48  *      DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA  false 1414 107
  49  * @run main/othervm -Djdk.tls.ephemeralDHKeySize=matched
  50  *      DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA  false 1894 267
  51  * @run main/othervm -Djdk.tls.ephemeralDHKeySize=1024
  52  *      DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA  false 1510 139
  53  *
  54  * @run main/othervm
  55  *      DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5  false 484 139
  56  * @run main/othervm -Djdk.tls.ephemeralDHKeySize=legacy
  57  *      DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5  false 388 107
  58  * @run main/othervm -Djdk.tls.ephemeralDHKeySize=matched
  59  *      DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5  false 484 139
  60  * @run main/othervm -Djdk.tls.ephemeralDHKeySize=1024
  61  *      DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5  false 484 139
  62  */
  63 
  64 /*
  65  * This is a simple hack to test key sizes of Diffie-Hellman key exchanging
  66  * during SSL/TLS handshaking.
  67  *
  68  * The record length of DH ServerKeyExchange and ClientKeyExchange.
  69  * ServerKeyExchange message are wrapped in ServerHello series messages, which
  70  * contains ServerHello, Certificate and ServerKeyExchange message.
  71  *
  72  *    struct {
  73  *        opaque dh_p<1..2^16-1>;
  74  *        opaque dh_g<1..2^16-1>;
  75  *        opaque dh_Ys<1..2^16-1>;
  76  *    } ServerDHParams;     // Ephemeral DH parameters
  77  *
  78  *    struct {
  79  *        select (PublicValueEncoding) {
  80  *            case implicit: struct { };
  81  *            case explicit: opaque dh_Yc<1..2^16-1>;
  82  *        } dh_public;
  83  *    } ClientDiffieHellmanPublic;
  84  *
  85  * Fomr above structures, it is clear that if the DH key size increasing 128
  86  * bits (16 bytes), the ServerHello series messages increases 48 bytes
  87  * (becuase dh_p, dh_g and dh_Ys each increase 16 bytes) and ClientKeyExchange
  88  * increases 16 bytes (because of the size increasing of dh_Yc).
  89  *
  90  * Here is a summary of the record length in the test case.
  91  *
  92  *            |  ServerHello Series  |  ClientKeyExchange | ServerHello Anon
  93  *   512-bit  |          1318 bytes  |           75 bytes |        292 bytes
  94  *   768-bit  |          1414 bytes  |          107 bytes |        388 bytes
  95  *  1024-bit  |          1510 bytes  |          139 bytes |        484 bytes
  96  *  2048-bit  |          1894 bytes  |          267 bytes |        484 bytes
  97  */
  98 
  99 import javax.net.ssl.*;
 100 import javax.net.ssl.SSLEngineResult.*;
 101 import java.io.*;
 102 import java.nio.*;
 103 import java.security.KeyStore;
 104 import java.security.KeyFactory;
 105 import java.security.Security;
 106 import java.security.cert.Certificate;
 107 import java.security.cert.CertificateFactory;
 108 import java.security.spec.PKCS8EncodedKeySpec;
 109 import java.security.interfaces.*;
 110 import java.util.Base64;
 111 
 112 public class DHEKeySizing {
 113 
 114     private final static boolean debug = true;
 115 
 116     // key length bias because of the stripping of leading zero bytes of
 117     // negotiated DH keys.
 118     //
 119     // This is an effort to mimum intermittent failure when we cannot
 120     // estimate what's the exact number of leading zero bytes of
 121     // negotiated DH keys.
 122     private final static int KEY_LEN_BIAS = 6;
 123 
 124     private SSLContext sslc;
 125     private SSLEngine ssle1;    // client
 126     private SSLEngine ssle2;    // server
 127 
 128     private ByteBuffer appOut1;         // write side of ssle1
 129     private ByteBuffer appIn1;          // read side of ssle1
 130     private ByteBuffer appOut2;         // write side of ssle2
 131     private ByteBuffer appIn2;          // read side of ssle2
 132 
 133     private ByteBuffer oneToTwo;        // "reliable" transport ssle1->ssle2
 134     private ByteBuffer twoToOne;        // "reliable" transport ssle2->ssle1
 135 
 136     /*
 137      * Where do we find the keystores?
 138      */
 139     // Certificates and key used in the test.
 140     static String trustedCertStr =
 141         "-----BEGIN CERTIFICATE-----\n" +
 142         "MIIC8jCCAdqgAwIBAgIEUjkuRzANBgkqhkiG9w0BAQUFADA7MR0wGwYDVQQLExRT\n" +
 143         "dW5KU1NFIFRlc3QgU2VyaXZjZTENMAsGA1UEChMESmF2YTELMAkGA1UEBhMCVVMw\n" +
 144         "HhcNMTMwOTE4MDQzODMxWhcNMTMxMjE3MDQzODMxWjA7MR0wGwYDVQQLExRTdW5K\n" +
 145         "U1NFIFRlc3QgU2VyaXZjZTENMAsGA1UEChMESmF2YTELMAkGA1UEBhMCVVMwggEi\n" +
 146         "MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCO+IGeaskJAvEcYc7pCl9neK3E\n" +
 147         "a28fwWLtChufYNaC9hQfZlUdETWYjV7fZJVJKT/oLzdDNMWuVA0LKXArpI3thLNK\n" +
 148         "QLXisdF9hKPlZRDazACL9kWUUtJ0FzpEySK4e8wW/z9FuU6e6iO19FbjxAfInJqk\n" +
 149         "3EDiEhB5g73S2vtvPCxgq2DvWw9TDl/LIqdKG2JCS93koXCCaHmQ7MrIOqHPd+8r\n" +
 150         "RbGpatXT9qyHKppUv9ATxVygO4rA794mgCFxpT+fkhz+NEB0twTkM65T1hnnOv5n\n" +
 151         "ZIxkcjBggt85UlZtnP3b9P7SYxsWIa46Oc38Od2f3YejfVg6B+PqPgWNl3+/AgMB\n" +
 152         "AAEwDQYJKoZIhvcNAQEFBQADggEBAAlrP6DFLRPSy0IgQhcI2i56tR/na8pezSte\n" +
 153         "ZHcCdaCZPDy4UP8mpLJ9QCjEB5VJv8hPm4xdK7ULnKGOGHgYqDpV2ZHvQlhV1woQ\n" +
 154         "TZGb/LM3c6kAs0j4j9KM2fq3iYUYexjIkS1KzsziflxMM6igS9BRMBR2LQyU+cYq\n" +
 155         "YEsFzkF7Aj2ET4v/+tgot9mRr2NioJcaJkdsPDpMU3IKB1cczfu+OuLQ/GCG0Fqu\n" +
 156         "6ijCeCqfnaAbemHbJeVZZ6Qgka3uC2YMntLBmLkhqEo1d9zGYLoh7oWL77y5ibQZ\n" +
 157         "LK5/H/zikcu579TWjlDHcqL3arCwBcrtsjSaPrRSWMrWV/6c0qw=\n" +
 158         "-----END CERTIFICATE-----";
 159 
 160     // Private key in the format of PKCS#8
 161     static String targetPrivateKey =
 162         "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCO+IGeaskJAvEc\n" +
 163         "Yc7pCl9neK3Ea28fwWLtChufYNaC9hQfZlUdETWYjV7fZJVJKT/oLzdDNMWuVA0L\n" +
 164         "KXArpI3thLNKQLXisdF9hKPlZRDazACL9kWUUtJ0FzpEySK4e8wW/z9FuU6e6iO1\n" +
 165         "9FbjxAfInJqk3EDiEhB5g73S2vtvPCxgq2DvWw9TDl/LIqdKG2JCS93koXCCaHmQ\n" +
 166         "7MrIOqHPd+8rRbGpatXT9qyHKppUv9ATxVygO4rA794mgCFxpT+fkhz+NEB0twTk\n" +
 167         "M65T1hnnOv5nZIxkcjBggt85UlZtnP3b9P7SYxsWIa46Oc38Od2f3YejfVg6B+Pq\n" +
 168         "PgWNl3+/AgMBAAECggEAPdb5Ycc4m4A9QBSCRcRpzbyiFLKPh0HDg1n65q4hOtYr\n" +
 169         "kAVYTVFTSF/lqGS+Ob3w2YIKujQKSUQrvCc5UHdFuHXMgxKIWbymK0+DAMb9SlYw\n" +
 170         "6lkkcWp9gx9E4dnJ/df2SAAxovvrKMuHlL1SFASHhVtPfH2URvSfUaANLDXxyYOs\n" +
 171         "8BX0Nr6wazhWjLjXo9yIGnKSvFfB8XisYcA78kEgas43zhmIGCDPqaYyyffOfRbx\n" +
 172         "pM1KNwGmlN86iWR1CbwA/wwhcMySWQueS+s7cHbpRqZIYJF9jEeELiwi0vxjealS\n" +
 173         "EMuHYedIRFMWaDIq9XyjrvXamHb0Z25jlXBNZHaM0QKBgQDE9adl+zAezR/n79vw\n" +
 174         "0XiX2Fx1UEo3ApZHuoA2Q/PcBk+rlKqqQ3IwTcy6Wo648wK7v6Nq7w5nEWcsf0dU\n" +
 175         "QA2Ng/AJEev/IfF34x7sKGYxtk1gcE0EuSBA3R+ocEZxnNw1Ryd5nUU24s8d4jCP\n" +
 176         "Mkothnyaim+zE2raDlEtVc0CaQKBgQC509av+02Uq5oMjzbQp5PBJfQFjATOQT15\n" +
 177         "eefYnVYurkQ1kcVfixkrO2ORhg4SjmI2Z5hJDgGtXdwgidpzkad+R2epS5qLMyno\n" +
 178         "lQVpY6bMpEZ7Mos0yQygxnm8uNohEcTExOe+nP5fNJVpzBsGmfeyYOhnPQlf6oqf\n" +
 179         "0cHizedb5wKBgQC/l5LyMil6HOGHlhzmIm3jj7VI7QR0hJC5T6N+phVml8ESUDjA\n" +
 180         "DYHbmSKouISTRtkG14FY+RiSjCxH7bvuKazFV2289PETquogTA/9e8MFYqfcQwG4\n" +
 181         "sXi9gBxWlnj/9a2EKiYtOB5nKLR/BlNkSHA93tAA6N+FXEMZwMmYhxk42QKBgAuY\n" +
 182         "HQgD3PZOsqDf+qKQIhbmAFCsSMx5o5VFtuJ8BpmJA/Z3ruHkMuDQpsi4nX4o5hXQ\n" +
 183         "5t6AAjjH52kcUMXvK40kdWJJtk3DFnVNfvXxYsHX6hHbuHXFqYUKfSP6QJnZmvZP\n" +
 184         "9smcz/4usLfWJUWHK740b6upUkFqx9Vq5/b3s9y3AoGAdM5TW7LkkOFsdMGVAUzR\n" +
 185         "9iXmCWElHTK2Pcp/3yqDBHSfiQx6Yp5ANyPnE9NBM0yauCfOyBB2oxLO4Rdv3Rqk\n" +
 186         "9V9kyR/YAGr7dJaPcQ7pZX0OpkzgueAOJYPrx5VUzPYUtklYV1ycFZTfKlpFCxT+\n" +
 187         "Ei6KUo0NXSdUIcB4yib1J10=";
 188 
 189     static char passphrase[] = "passphrase".toCharArray();
 190 
 191     /*
 192      * Majority of the test case is here, setup is done below.
 193      */
 194 
 195     private void createSSLEngines() throws Exception {
 196         ssle1 = sslc.createSSLEngine("client", 1);
 197         ssle1.setUseClientMode(true);
 198 
 199         ssle2 = sslc.createSSLEngine("server", 2);
 200         ssle2.setUseClientMode(false);
 201     }
 202 
 203     private boolean isHandshaking(SSLEngine e) {
 204         return (e.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING);
 205     }
 206 
 207     private void checkResult(ByteBuffer bbIn, ByteBuffer bbOut,
 208             SSLEngineResult result,
 209             Status status, HandshakeStatus hsStatus,
 210             int consumed, int produced)
 211             throws Exception {
 212 
 213         if ((status != null) && (result.getStatus() != status)) {
 214             throw new Exception("Unexpected Status: need = " + status +
 215                 " got = " + result.getStatus());
 216         }
 217 
 218         if ((hsStatus != null) && (result.getHandshakeStatus() != hsStatus)) {
 219             throw new Exception("Unexpected hsStatus: need = " + hsStatus +
 220                 " got = " + result.getHandshakeStatus());
 221         }
 222 
 223         if ((consumed != -1) && (consumed != result.bytesConsumed())) {
 224             throw new Exception("Unexpected consumed: need = " + consumed +
 225                 " got = " + result.bytesConsumed());
 226         }
 227 
 228         if ((produced != -1) && (produced != result.bytesProduced())) {
 229             throw new Exception("Unexpected produced: need = " + produced +
 230                 " got = " + result.bytesProduced());
 231         }
 232 
 233         if ((consumed != -1) && (bbIn.position() != result.bytesConsumed())) {
 234             throw new Exception("Consumed " + bbIn.position() +
 235                 " != " + consumed);
 236         }
 237 
 238         if ((produced != -1) && (bbOut.position() != result.bytesProduced())) {
 239             throw new Exception("produced " + bbOut.position() +
 240                 " != " + produced);
 241         }
 242     }
 243 
 244     private void test(String cipherSuite, boolean exportable,
 245             int lenServerKeyEx, int lenClientKeyEx) throws Exception {
 246 
 247         createSSLEngines();
 248         createBuffers();
 249 
 250         SSLEngineResult result1;        // ssle1's results from last operation
 251         SSLEngineResult result2;        // ssle2's results from last operation
 252 
 253         String[] suites = new String [] {cipherSuite};
 254 
 255         ssle1.setEnabledCipherSuites(suites);
 256         ssle2.setEnabledCipherSuites(suites);
 257 
 258         log("======================================");
 259         log("===================");
 260         log("client hello");
 261         result1 = ssle1.wrap(appOut1, oneToTwo);
 262         checkResult(appOut1, oneToTwo, result1,
 263             Status.OK, HandshakeStatus.NEED_UNWRAP, 0, -1);
 264         oneToTwo.flip();
 265 
 266         result2 = ssle2.unwrap(oneToTwo, appIn2);
 267         checkResult(oneToTwo, appIn2, result2,
 268             Status.OK, HandshakeStatus.NEED_TASK, result1.bytesProduced(), 0);
 269         runDelegatedTasks(ssle2);
 270         oneToTwo.compact();
 271 
 272         log("===================");
 273         log("ServerHello");
 274         result2 = ssle2.wrap(appOut2, twoToOne);
 275         checkResult(appOut2, twoToOne, result2,
 276             Status.OK, HandshakeStatus.NEED_UNWRAP, 0, -1);
 277         twoToOne.flip();
 278 
 279         log("Message length of ServerHello series: " + twoToOne.remaining());
 280         if (twoToOne.remaining() < (lenServerKeyEx - KEY_LEN_BIAS) ||
 281                 twoToOne.remaining() > lenServerKeyEx) {
 282             throw new Exception(
 283                 "Expected to generate ServerHello series messages of " +
 284                 lenServerKeyEx + " bytes, but not " + twoToOne.remaining());
 285         }
 286 
 287         result1 = ssle1.unwrap(twoToOne, appIn1);
 288         checkResult(twoToOne, appIn1, result1,
 289             Status.OK, HandshakeStatus.NEED_TASK, result2.bytesProduced(), 0);
 290         runDelegatedTasks(ssle1);
 291         twoToOne.compact();
 292 
 293         log("===================");
 294         log("Key Exchange");
 295         result1 = ssle1.wrap(appOut1, oneToTwo);
 296         checkResult(appOut1, oneToTwo, result1,
 297             Status.OK, HandshakeStatus.NEED_WRAP, 0, -1);
 298         oneToTwo.flip();
 299 
 300         log("Message length of ClientKeyExchange: " + oneToTwo.remaining());
 301         if (oneToTwo.remaining() < (lenClientKeyEx - KEY_LEN_BIAS) ||
 302                 oneToTwo.remaining() > lenClientKeyEx) {
 303             throw new Exception(
 304                 "Expected to generate ClientKeyExchange message of " +
 305                 lenClientKeyEx + " bytes, but not " + oneToTwo.remaining());
 306         }
 307         result2 = ssle2.unwrap(oneToTwo, appIn2);
 308         checkResult(oneToTwo, appIn2, result2,
 309             Status.OK, HandshakeStatus.NEED_TASK, result1.bytesProduced(), 0);
 310         runDelegatedTasks(ssle2);
 311         oneToTwo.compact();
 312 
 313         log("===================");
 314         log("Client CCS");
 315         result1 = ssle1.wrap(appOut1, oneToTwo);
 316         checkResult(appOut1, oneToTwo, result1,
 317             Status.OK, HandshakeStatus.NEED_WRAP, 0, -1);
 318         oneToTwo.flip();
 319 
 320         result2 = ssle2.unwrap(oneToTwo, appIn2);
 321         checkResult(oneToTwo, appIn2, result2,
 322             Status.OK, HandshakeStatus.NEED_UNWRAP,
 323             result1.bytesProduced(), 0);
 324         oneToTwo.compact();
 325 
 326         log("===================");
 327         log("Client Finished");
 328         result1 = ssle1.wrap(appOut1, oneToTwo);
 329         checkResult(appOut1, oneToTwo, result1,
 330             Status.OK, HandshakeStatus.NEED_UNWRAP, 0, -1);
 331         oneToTwo.flip();
 332 
 333         result2 = ssle2.unwrap(oneToTwo, appIn2);
 334         checkResult(oneToTwo, appIn2, result2,
 335             Status.OK, HandshakeStatus.NEED_WRAP,
 336             result1.bytesProduced(), 0);
 337         oneToTwo.compact();
 338 
 339         log("===================");
 340         log("Server CCS");
 341         result2 = ssle2.wrap(appOut2, twoToOne);
 342         checkResult(appOut2, twoToOne, result2,
 343             Status.OK, HandshakeStatus.NEED_WRAP, 0, -1);
 344         twoToOne.flip();
 345 
 346         result1 = ssle1.unwrap(twoToOne, appIn1);
 347         checkResult(twoToOne, appIn1, result1,
 348             Status.OK, HandshakeStatus.NEED_UNWRAP, result2.bytesProduced(), 0);
 349         twoToOne.compact();
 350 
 351         log("===================");
 352         log("Server Finished");
 353         result2 = ssle2.wrap(appOut2, twoToOne);
 354         checkResult(appOut2, twoToOne, result2,
 355             Status.OK, HandshakeStatus.FINISHED, 0, -1);
 356         twoToOne.flip();
 357 
 358         result1 = ssle1.unwrap(twoToOne, appIn1);
 359         checkResult(twoToOne, appIn1, result1,
 360             Status.OK, HandshakeStatus.FINISHED, result2.bytesProduced(), 0);
 361         twoToOne.compact();
 362 
 363         log("===================");
 364         log("Check Session/Ciphers");
 365         String cs = ssle1.getSession().getCipherSuite();
 366         if (!cs.equals(suites[0])) {
 367             throw new Exception("suites not equal: " + cs + "/" + suites[0]);
 368         }
 369 
 370         cs = ssle2.getSession().getCipherSuite();
 371         if (!cs.equals(suites[0])) {
 372             throw new Exception("suites not equal: " + cs + "/" + suites[0]);
 373         }
 374 
 375         log("===================");
 376         log("Done with SSL/TLS handshaking");
 377     }
 378 
 379     public static void main(String args[]) throws Exception {
 380         // reset the security property to make sure that the algorithms
 381         // and keys used in this test are not disabled.
 382         Security.setProperty("jdk.tls.disabledAlgorithms", "");
 383 
 384         if (args.length != 4) {
 385             System.out.println(
 386                 "Usage: java DHEKeySizing cipher-suite " +
 387                 "exportable(true|false)\n" +
 388                 "    size-of-server-hello-record size-of-client-key-exchange");
 389             throw new Exception("Incorrect usage!");
 390         }
 391 
 392         (new DHEKeySizing()).test(args[0],
 393                 Boolean.parseBoolean(args[1]),
 394                 Integer.parseInt(args[2]),
 395                 Integer.parseInt(args[3]));
 396         System.out.println("Test Passed.");
 397     }
 398 
 399     /*
 400      * **********************************************************
 401      * Majority of the test case is above, below is just setup stuff
 402      * **********************************************************
 403      */
 404 
 405     public DHEKeySizing() throws Exception {
 406         sslc = getSSLContext();
 407     }
 408 
 409     /*
 410      * Create an initialized SSLContext to use for this test.
 411      */
 412     private SSLContext getSSLContext() throws Exception {
 413 
 414         // generate certificate from cert string
 415         CertificateFactory cf = CertificateFactory.getInstance("X.509");
 416 
 417         // create a key store
 418         KeyStore ts = KeyStore.getInstance("JKS");
 419         KeyStore ks = KeyStore.getInstance("JKS");
 420         ts.load(null, null);
 421         ks.load(null, null);
 422 
 423         // import the trused cert
 424         ByteArrayInputStream is =
 425                     new ByteArrayInputStream(trustedCertStr.getBytes());
 426         Certificate trusedCert = cf.generateCertificate(is);
 427         is.close();
 428         ts.setCertificateEntry("rsa-trusted-2048", trusedCert);
 429 
 430         // generate the private key.
 431         String keySpecStr = targetPrivateKey;
 432         PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
 433                             Base64.getMimeDecoder().decode(keySpecStr));
 434         KeyFactory kf = KeyFactory.getInstance("RSA");
 435         RSAPrivateKey priKey = (RSAPrivateKey)kf.generatePrivate(priKeySpec);
 436 
 437         Certificate[] chain = new Certificate[1];
 438         chain[0] = trusedCert;
 439 
 440         // import the key entry.
 441         ks.setKeyEntry("rsa-key-2048", priKey, passphrase, chain);
 442 
 443         // create SSL context
 444         KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
 445         kmf.init(ks, passphrase);
 446 
 447         TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
 448         tmf.init(ts);
 449 
 450         SSLContext sslCtx = SSLContext.getInstance("TLSv1");
 451         sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
 452 
 453         return sslCtx;
 454     }
 455 
 456     private void createBuffers() {
 457         // Size the buffers as appropriate.
 458 
 459         SSLSession session = ssle1.getSession();
 460         int appBufferMax = session.getApplicationBufferSize();
 461         int netBufferMax = session.getPacketBufferSize();
 462 
 463         appIn1 = ByteBuffer.allocateDirect(appBufferMax + 50);
 464         appIn2 = ByteBuffer.allocateDirect(appBufferMax + 50);
 465 
 466         oneToTwo = ByteBuffer.allocateDirect(netBufferMax);
 467         twoToOne = ByteBuffer.allocateDirect(netBufferMax);
 468 
 469         appOut1 = ByteBuffer.wrap("Hi Engine2, I'm SSLEngine1".getBytes());
 470         appOut2 = ByteBuffer.wrap("Hello Engine1, I'm SSLEngine2".getBytes());
 471 
 472         log("AppOut1 = " + appOut1);
 473         log("AppOut2 = " + appOut2);
 474         log("");
 475     }
 476 
 477     private static void runDelegatedTasks(SSLEngine engine) throws Exception {
 478 
 479         Runnable runnable;
 480         while ((runnable = engine.getDelegatedTask()) != null) {
 481             log("running delegated task...");
 482             runnable.run();
 483         }
 484     }
 485 
 486     private static void log(String str) {
 487         if (debug) {
 488             System.out.println(str);
 489         }
 490     }
 491 }