summaryrefslogtreecommitdiff
path: root/gnu/javax/net/ssl/provider/AbstractHandshake.java
blob: 6166bbde28da4d716174e3eda46fbd3e4fa3705d (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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
/* AbstractHandshake.java -- abstract handshake handler.
   Copyright (C) 2006  Free Software Foundation, Inc.

This file is a part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version.  */


package gnu.javax.net.ssl.provider;

import gnu.classpath.ByteArray;
import gnu.classpath.Configuration;
import gnu.classpath.debug.Component;
import gnu.classpath.debug.SystemLogger;
import gnu.java.security.prng.IRandom;
import gnu.java.security.prng.LimitReachedException;

import java.nio.ByteBuffer;
import java.security.DigestException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.HashMap;
import java.util.logging.Logger;

import javax.crypto.KeyAgreement;
import javax.crypto.interfaces.DHPrivateKey;
import javax.crypto.interfaces.DHPublicKey;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;

/**
 * The base interface for handshake implementations. Concrete
 * subclasses of this class (one for the server, one for the client)
 * handle the HANDSHAKE content-type in communications.
 */
public abstract class AbstractHandshake
{
  protected static final SystemLogger logger = SystemLogger.SYSTEM;

  /**
   * "server finished" -- TLS 1.0 and later
   */
  protected static final byte[] SERVER_FINISHED
    = new byte[] {
      115, 101, 114, 118, 101, 114,  32, 102, 105, 110, 105, 115,
      104, 101, 100   
    };
  
  /**
   * "client finished" -- TLS 1.0 and later
   */
  protected static final byte[] CLIENT_FINISHED
    = new byte[] {
       99, 108, 105, 101, 110, 116,  32, 102, 105, 110, 105, 115,
      104, 101, 100
    };
  
  /**
   * "key expansion" -- TLS 1.0 and later
   */
  private static final byte[] KEY_EXPANSION =
    new byte[] { 107, 101, 121,  32, 101, 120, 112,
                  97, 110, 115, 105, 111, 110 };
  
  /**
   * "master secret" -- TLS 1.0 and later
   */
  private static final byte[] MASTER_SECRET
    = new byte[] {
      109,  97, 115, 116, 101, 114,  32, 115, 101,  99, 114, 101, 116
    };
  
  /**
   * SSL 3.0; the string "CLNT"
   */
  private static final byte[] SENDER_CLIENT
    = new byte[] { 0x43, 0x4C, 0x4E, 0x54 };
  
  /**
   * SSL 3.0; the string "SRVR"
   */
  private static final byte[] SENDER_SERVER
    = new byte[] { 0x53, 0x52, 0x56, 0x52 };
  
  /**
   * SSL 3.0; the value 0x36 40 (for SHA-1 hashes) or 48 (for MD5 hashes)
   * times.
   */
  private static final byte[] PAD1 = new byte[48];
  
  /**
   * SSL 3.0; the value 0x5c 40 (for SHA-1 hashes) or 48 (for MD5 hashes)
   * times.
   */
  private static final byte[] PAD2 = new byte[48];

  static
  {
    Arrays.fill(PAD1, SSLHMac.PAD1);
    Arrays.fill(PAD2, SSLHMac.PAD2);
  }
  
  /**
   * The currently-read handshake messages. There may be zero, or
   * multiple, handshake messages in this buffer.
   */
  protected ByteBuffer handshakeBuffer;

  /**
   * The offset into `handshakeBuffer' where the first unread
   * handshake message resides.
   */
  protected int handshakeOffset;

  protected MessageDigest sha;
  protected MessageDigest md5;
  
  protected KeyAgreement keyAgreement;
  protected byte[] preMasterSecret;
  
  protected AbstractHandshake() throws NoSuchAlgorithmException
  {
    sha = MessageDigest.getInstance("SHA-1");
    md5 = MessageDigest.getInstance("MD5");
  }
  
  /**
   * Handles the next input message in the handshake. This is called
   * in response to a call to {@link javax.net.ssl.SSLEngine#unwrap}
   * for a message with content-type HANDSHAKE.
   *
   * @param record The input record. The callee should not assume that
   * the record's buffer is writable, and should not try to use it for
   * output or temporary storage.
   * @return An {@link SSLEngineResult} describing the result.
   */
  public final HandshakeStatus handleInput (ByteBuffer fragment)
    throws SSLException
  {
    HandshakeStatus status = status();
    if (status != HandshakeStatus.NEED_UNWRAP)
      return status;

    // Try to read another...
    if (!pollHandshake(fragment))
      return HandshakeStatus.NEED_UNWRAP;

    while (hasMessage() && status == HandshakeStatus.NEED_UNWRAP)
      {
        int pos = handshakeOffset;
        status = implHandleInput();
        int len = handshakeOffset - pos;
        if (len == 0)
          {
            // Don't bother; the impl is just telling us to go around
            // again.
            continue;
          }
        if (doHash())
          {
            if (Debug.DEBUG)
              logger.logv(Component.SSL_HANDSHAKE, "hashing output\n{0}",
                          Util.hexDump((ByteBuffer) handshakeBuffer
                                       .duplicate().position(pos)
                                       .limit(pos+len), " >> "));
            sha.update((ByteBuffer) handshakeBuffer.duplicate()
                       .position(pos).limit(pos+len));
            md5.update((ByteBuffer) handshakeBuffer.duplicate()
                       .position(pos).limit(pos+len));
          }
      }
    return status;
  }

  /**
   * Called to process more handshake data. This method will be called
   * repeatedly while there is remaining handshake data, and while the
   * status is 
   * @return
   * @throws SSLException
   */
  protected abstract HandshakeStatus implHandleInput()
    throws SSLException;
  
  /**
   * Produce more handshake output. This is called in response to a
   * call to {@link javax.net.ssl.SSLEngine#wrap}, when the handshake
   * is still in progress.
   *
   * @param record The output record; the callee should put its output
   * handshake message (or a part of it) in the argument's
   * <code>fragment</code>, and should set the record length
   * appropriately.
   * @return An {@link SSLEngineResult} describing the result.
   */
  public final SSLEngineResult.HandshakeStatus handleOutput (ByteBuffer fragment)
    throws SSLException
  {
    int orig = fragment.position();
    SSLEngineResult.HandshakeStatus status = implHandleOutput(fragment);
    if (doHash())
      {
        if (Debug.DEBUG)
          logger.logv(Component.SSL_HANDSHAKE, "hashing output:\n{0}",
                      Util.hexDump((ByteBuffer) fragment.duplicate().flip().position(orig), " >> "));
        sha.update((ByteBuffer) fragment.duplicate().flip().position(orig));
        md5.update((ByteBuffer) fragment.duplicate().flip().position(orig));
      }
    return status;
  }
  
  /**
   * Called to implement the underlying output handling. The callee should
   * attempt to fill the given buffer as much as it can; this can include
   * multiple, and even partial, handshake messages.
   * 
   * @param fragment The buffer the callee should write handshake messages to.
   * @return The new status of the handshake.
   * @throws SSLException If an error occurs processing the output message.
   */
  protected abstract SSLEngineResult.HandshakeStatus implHandleOutput (ByteBuffer fragment)
    throws SSLException;
  
  /**
   * Return a new instance of input security parameters, initialized with
   * the session key. It is, of course, only valid to invoke this method
   * once the handshake is complete, and the session keys established.
   * 
   * <p>In the presence of a well-behaving peer, this should be called once
   * the <code>ChangeCipherSpec</code> message is recieved.
   * 
   * @return The input parameters for the newly established session.
   * @throws SSLException If the handshake is not complete.
   */
  abstract InputSecurityParameters getInputParams() throws SSLException;

  /**
   * Return a new instance of output security parameters, initialized with
   * the session key. This should be called after the
   * <code>ChangeCipherSpec</code> message is sent to the peer.
   * 
   * @return The output parameters for the newly established session.
   * @throws SSLException If the handshake is not complete.
   */
  abstract OutputSecurityParameters getOutputParams() throws SSLException;
  
  /**
   * Used by the skeletal code to query the current status of the handshake.
   * This <em>should</em> be the same value as returned by the previous call
   * to {@link #implHandleOutput(ByteBuffer)} or {@link
   *  #implHandleInput(ByteBuffer)}.
   * 
   * @return The current handshake status.
   */
  abstract SSLEngineResult.HandshakeStatus status();
  
  /**
   * Handle an SSLv2 client hello. This is only used by SSL servers.
   * 
   * @param hello The hello message.
   */
  abstract void handleV2Hello(ByteBuffer hello) throws SSLException;
  
  /**
   * Attempt to read the next handshake message from the given
   * record. If only a partial handshake message is available, then
   * this method saves the incoming bytes and returns false. If a
   * complete handshake is read, or if there was one buffered in the
   * handshake buffer, this method returns true, and `handshakeBuffer'
   * can be used to read the handshake.
   *
   * @param record The input record.
   * @return True if a complete handshake is present in the buffer;
   * false if only a partial one.
   */
  protected boolean pollHandshake (final ByteBuffer fragment)
  {
    // Allocate space for the new fragment.
    if (handshakeBuffer == null
        || handshakeBuffer.remaining() < fragment.remaining())
      {
        // We need space for anything still unread in the handshake
        // buffer...
        int len = ((handshakeBuffer == null) ? 0
                   : handshakeBuffer.position() - handshakeOffset);

        // Plus room for the incoming record.
        len += fragment.remaining();
        reallocateBuffer(len);
      }

    if (Debug.DEBUG)
      logger.logv(Component.SSL_HANDSHAKE, "inserting {0} into {1}",
                  fragment, handshakeBuffer);
    
    // Put the fragment into the buffer.
    handshakeBuffer.put(fragment);

    return hasMessage();
  }
  
  protected boolean doHash()
  {
    return true;
  }

  /**
   * Tell if the handshake buffer currently has a full handshake
   * message.
   */
  protected boolean hasMessage()
  {
    if (handshakeBuffer == null)
      return false;
    ByteBuffer tmp = handshakeBuffer.duplicate();
    tmp.flip();
    tmp.position(handshakeOffset);
    if (Debug.DEBUG)
      logger.logv(Component.SSL_HANDSHAKE, "current buffer: {0}; test buffer {1}",
                  handshakeBuffer, tmp);
    if (tmp.remaining() < 4)
      return false;
    Handshake handshake = new Handshake(tmp.slice());
    if (Debug.DEBUG)
      logger.logv(Component.SSL_HANDSHAKE, "handshake len:{0} remaining:{1}",
                  handshake.length(), tmp.remaining());
    return (handshake.length() <= tmp.remaining() - 4);
  }

  /**
   * Reallocate the handshake buffer so it can hold `totalLen'
   * bytes. The smallest buffer allocated is 1024 bytes, and the size
   * doubles from there until the buffer is sufficiently large.
   */
  private void reallocateBuffer (final int totalLen)
  {
    int len = handshakeBuffer == null ? -1
                                      : handshakeBuffer.capacity() - (handshakeBuffer.limit() - handshakeOffset);
    if (len >= totalLen)
      {
        // Big enough; no need to reallocate; but maybe shift the contents
        // down.
        if (handshakeOffset > 0)
          {
            ByteBuffer tmp = handshakeBuffer.duplicate();
            tmp.flip();
            tmp.position(handshakeOffset);
            handshakeBuffer.position(0);
            handshakeBuffer.put(tmp);
            handshakeOffset = 0;
          }
        return;
      }

    // Start at 1K (probably the system's page size). Double the size
    // from there.
    len = 1024;
    while (len < totalLen)
      len = len << 1;
    ByteBuffer newBuf = ByteBuffer.allocate (len);

    // Copy the unread bytes from the old buffer.
    if (handshakeBuffer != null)
      {
        handshakeBuffer.flip ();
        handshakeBuffer.position(handshakeOffset);
        newBuf.put(handshakeBuffer);
      }
    handshakeBuffer = newBuf;

    // We just put only unread handshake messages in the new buffer;
    // the offset of the next one is now zero.
    handshakeOffset = 0;
  }

  /**
   * Generate a certificate verify message for SSLv3. In SSLv3, a different
   * algorithm was used to generate this value was subtly different than
   * that used in TLSv1.0 and later. In TLSv1.0 and later, this value is
   * just the digest over the handshake messages.
   * 
   * <p>SSLv3 uses the algorithm:
   * 
   * <pre>
CertificateVerify.signature.md5_hash
  MD5(master_secret + pad_2 +
      MD5(handshake_messages + master_secret + pad_1));
Certificate.signature.sha_hash
  SHA(master_secret + pad_2 +
      SHA(handshake_messages + master_secret + pad_1));</pre>
   * 
   * @param md5 The running MD5 hash of the handshake.
   * @param sha The running SHA-1 hash of the handshake.
   * @param session The current session being negotiated.
   * @return The computed to-be-signed value.
   */
  protected byte[] genV3CertificateVerify(MessageDigest md5,
                                          MessageDigest sha,
                                          SessionImpl session)
  {
    byte[] md5value = null;
    if (session.suite.signatureAlgorithm() == SignatureAlgorithm.RSA)
      {
        md5.update(session.privateData.masterSecret);
        md5.update(SSLHMac.PAD1);
        byte[] tmp = md5.digest();
        md5.reset();
        md5.update(session.privateData.masterSecret);
        md5.update(SSLHMac.PAD2);
        md5.update(tmp);
        md5value = md5.digest();
      }
    
    sha.update(session.privateData.masterSecret);
    sha.update(SSLHMac.PAD1);
    byte[] tmp = sha.digest();
    sha.reset();
    sha.update(session.privateData.masterSecret);
    sha.update(SSLHMac.PAD2);
    sha.update(tmp);
    byte[] shavalue = sha.digest();
    
    if (md5value != null)
      return Util.concat(md5value, shavalue);
    
    return shavalue;
  }
  
  /**
   * Generate the session keys from the computed master secret.
   * 
   * @param clientRandom The client's nonce.
   * @param serverRandom The server's nonce.
   * @param session The session being established.
   * @return The derived keys.
   */
  protected byte[][] generateKeys(Random clientRandom, Random serverRandom,
                                  SessionImpl session)
  {
    int maclen = 20; // SHA-1.
    if (session.suite.macAlgorithm() == MacAlgorithm.MD5)
      maclen = 16;
    int ivlen = 0;
    if (session.suite.cipherAlgorithm() == CipherAlgorithm.DES
        || session.suite.cipherAlgorithm() == CipherAlgorithm.DESede)
      ivlen = 8;
    if (session.suite.cipherAlgorithm() == CipherAlgorithm.AES)
      ivlen = 16;
    int keylen = session.suite.keyLength();
    
    byte[][] keys = new byte[6][];
    keys[0] = new byte[maclen]; // client_write_MAC_secret
    keys[1] = new byte[maclen]; // server_write_MAC_secret
    keys[2] = new byte[keylen]; // client_write_key
    keys[3] = new byte[keylen]; // server_write_key
    keys[4] = new byte[ivlen];  // client_write_iv
    keys[5] = new byte[ivlen];  // server_write_iv
    
    IRandom prf = null;
    if (session.version == ProtocolVersion.SSL_3)
      {
        byte[] seed = new byte[clientRandom.length()
                               + serverRandom.length()];
        serverRandom.buffer().get(seed, 0, serverRandom.length());
        clientRandom.buffer().get(seed, serverRandom.length(),
                                  clientRandom.length());
        prf = new SSLRandom();
        HashMap<String,byte[]> attr = new HashMap<String,byte[]>(2);
        attr.put(SSLRandom.SECRET, session.privateData.masterSecret);
        attr.put(SSLRandom.SEED, seed);
        prf.init(attr);
      }
    else
      {
        byte[] seed = new byte[KEY_EXPANSION.length
                               + clientRandom.length()
                               + serverRandom.length()];
        System.arraycopy(KEY_EXPANSION, 0, seed, 0, KEY_EXPANSION.length);
        serverRandom.buffer().get(seed, KEY_EXPANSION.length,
                                  serverRandom.length());
        clientRandom.buffer().get(seed, (KEY_EXPANSION.length
                                         + serverRandom.length()),
                                  clientRandom.length());
        
        prf = new TLSRandom();
        HashMap<String,byte[]> attr = new HashMap<String,byte[]>(2);
        attr.put(TLSRandom.SECRET, session.privateData.masterSecret);
        attr.put(TLSRandom.SEED, seed);
        prf.init(attr);
      }
    
    try
      {
        prf.nextBytes(keys[0], 0, keys[0].length);
        prf.nextBytes(keys[1], 0, keys[1].length);
        prf.nextBytes(keys[2], 0, keys[2].length);
        prf.nextBytes(keys[3], 0, keys[3].length);
        prf.nextBytes(keys[4], 0, keys[4].length);
        prf.nextBytes(keys[5], 0, keys[5].length);
      }
    catch (LimitReachedException lre)
      {
        // Won't happen with our implementation.
        throw new Error(lre);
      }
    
    if (Debug.DEBUG_KEY_EXCHANGE)
      logger.logv(Component.SSL_KEY_EXCHANGE,
                  "keys generated;\n  [0]: {0}\n  [1]: {1}\n  [2]: {2}\n" +
                  "  [3]: {3}\n  [4]: {4}\n  [5]: {5}",
                  Util.toHexString(keys[0], ':'),
                  Util.toHexString(keys[1], ':'),
                  Util.toHexString(keys[2], ':'),
                  Util.toHexString(keys[3], ':'),
                  Util.toHexString(keys[4], ':'),
                  Util.toHexString(keys[5], ':'));
    return keys;
  }
  
  /**
   * Generate a "finished" message. The hashes passed in are modified
   * by this function, so they should be clone copies of the digest if
   * the hash function needs to be used more.
   * 
   * @param md5 The MD5 computation.
   * @param sha The SHA-1 computation.
   * @param isClient Whether or not the client-side finished message is
   *  being computed.
   * @param session The current session.
   * @return A byte buffer containing the computed finished message.
   */
  protected ByteBuffer generateFinished(MessageDigest md5,
                                        MessageDigest sha,
                                        boolean isClient,
                                        SessionImpl session)
  {
    ByteBuffer finishedBuffer = null;
    if (session.version.compareTo(ProtocolVersion.TLS_1) >= 0)
      {
        finishedBuffer = ByteBuffer.allocate(12);
        TLSRandom prf = new TLSRandom();
        byte[] md5val = md5.digest();
        byte[] shaval = sha.digest();
        if (Debug.DEBUG)
          logger.logv(Component.SSL_HANDSHAKE, "finished md5:{0} sha:{1}",
                      Util.toHexString(md5val, ':'),
                      Util.toHexString(shaval, ':'));
        byte[] seed = new byte[CLIENT_FINISHED.length
                               + md5val.length
                               + shaval.length];
        if (isClient)
          System.arraycopy(CLIENT_FINISHED, 0, seed, 0, CLIENT_FINISHED.length);
        else
          System.arraycopy(SERVER_FINISHED, 0, seed, 0, SERVER_FINISHED.length);
        System.arraycopy(md5val, 0,
                         seed, CLIENT_FINISHED.length,
                         md5val.length);
        System.arraycopy(shaval, 0,
                         seed, CLIENT_FINISHED.length + md5val.length,
                         shaval.length);
        HashMap<String, Object> params = new HashMap<String, Object>(2);
        params.put(TLSRandom.SECRET, session.privateData.masterSecret);
        params.put(TLSRandom.SEED, seed);
        prf.init(params);
        byte[] buf = new byte[12];
        prf.nextBytes(buf, 0, buf.length);
        finishedBuffer.put(buf).position(0);
      }
    else
      {
        // The SSLv3 algorithm is:
        //
        //   enum { client(0x434C4E54), server(0x53525652) } Sender;
        //
        //   struct {
        //     opaque md5_hash[16];
        //     opaque sha_hash[20];
        //   } Finished;
        //
        //   md5_hash       MD5(master_secret + pad2 +
        //                      MD5(handshake_messages + Sender +
        //                          master_secret + pad1));
        //   sha_hash        SHA(master_secret + pad2 +
        //                       SHA(handshake_messages + Sender +
        //                           master_secret + pad1));
        //

        finishedBuffer = ByteBuffer.allocate(36);
        
        md5.update(isClient ? SENDER_CLIENT : SENDER_SERVER);
        md5.update(session.privateData.masterSecret);
        md5.update(PAD1);
        
        byte[] tmp = md5.digest();
        md5.reset();
        md5.update(session.privateData.masterSecret);
        md5.update(PAD2);
        md5.update(tmp);
        finishedBuffer.put(md5.digest());
        
        sha.update(isClient ? SENDER_CLIENT : SENDER_SERVER);
        sha.update(session.privateData.masterSecret);
        sha.update(PAD1, 0, 40);
        
        tmp = sha.digest();
        sha.reset();
        sha.update(session.privateData.masterSecret);
        sha.update(PAD2, 0, 40);
        sha.update(tmp);
        finishedBuffer.put(sha.digest()).position(0);
      }
    return finishedBuffer;
  }
  
  protected void initDiffieHellman(DHPrivateKey dhKey, SecureRandom random)
    throws SSLException
  {
    try
      {
        keyAgreement = KeyAgreement.getInstance("DH");
        keyAgreement.init(dhKey, random);
      }
    catch (InvalidKeyException ike)
      {
        throw new SSLException(ike);
      }
    catch (NoSuchAlgorithmException nsae)
      {
        throw new SSLException(nsae);
      }
  }
  
  protected void diffieHellmanPhase1(DHPublicKey dhKey) throws SSLException
  {
    try
      {
        keyAgreement.doPhase(dhKey, false);
      }
    catch (InvalidKeyException ike)
      {
        throw new SSLException(ike);
      }
  }
  
  protected void diffieHellmanPhase2(DHPublicKey dhKey) throws SSLException
  {
    try
      {
        keyAgreement.doPhase(dhKey, true);
        preMasterSecret = keyAgreement.generateSecret();
      }
    catch (InvalidKeyException ike)
      {
        throw new SSLException(ike);
      }
  }
  
  protected void generateMasterSecret(Random clientRandom,
                                      Random serverRandom,
                                      SessionImpl session)
    throws SSLException
  {
    if (Debug.DEBUG_KEY_EXCHANGE)
      logger.logv(Component.SSL_KEY_EXCHANGE, "preMasterSecret:\n{0}",
                  new ByteArray(preMasterSecret));
    
    if (session.version == ProtocolVersion.SSL_3)
      {
        try
          {
            MessageDigest _md5 = MessageDigest.getInstance("MD5");
            MessageDigest _sha = MessageDigest.getInstance("SHA");
            session.privateData.masterSecret = new byte[48];
            
            _sha.update((byte) 'A');
            _sha.update(preMasterSecret);
            _sha.update(clientRandom.buffer());
            _sha.update(serverRandom.buffer());
            _md5.update(preMasterSecret);
            _md5.update(_sha.digest());
            _md5.digest(session.privateData.masterSecret, 0, 16);
            
            _sha.update((byte) 'B');
            _sha.update((byte) 'B');
            _sha.update(preMasterSecret);
            _sha.update(clientRandom.buffer());
            _sha.update(serverRandom.buffer());
            _md5.update(preMasterSecret);
            _md5.update(_sha.digest());
            _md5.digest(session.privateData.masterSecret, 16, 16);

            _sha.update((byte) 'C');
            _sha.update((byte) 'C');
            _sha.update((byte) 'C');
            _sha.update(preMasterSecret);
            _sha.update(clientRandom.buffer());
            _sha.update(serverRandom.buffer());
            _md5.update(preMasterSecret);
            _md5.update(_sha.digest());
            _md5.digest(session.privateData.masterSecret, 32, 16);
          }
        catch (DigestException de)
          {
            throw new SSLException(de);
          }
        catch (NoSuchAlgorithmException nsae)
          {
            throw new SSLException(nsae);
          }
      }
    else // TLSv1.0 and later
      {
        byte[] seed = new byte[clientRandom.length()
                               + serverRandom.length()
                               + MASTER_SECRET.length];
        System.arraycopy(MASTER_SECRET, 0, seed, 0, MASTER_SECRET.length);
        clientRandom.buffer().get(seed, MASTER_SECRET.length,
                                  clientRandom.length());
        serverRandom.buffer().get(seed,
                                  MASTER_SECRET.length + clientRandom.length(),
                                  serverRandom.length());
        TLSRandom prf = new TLSRandom();
        HashMap<String,byte[]> attr = new HashMap<String,byte[]>(2);
        attr.put(TLSRandom.SECRET, preMasterSecret);
        attr.put(TLSRandom.SEED, seed);
        prf.init(attr);
        
        session.privateData.masterSecret = new byte[48];
        prf.nextBytes(session.privateData.masterSecret, 0, 48);
      }
    
    if (Debug.DEBUG_KEY_EXCHANGE)
      logger.log(Component.SSL_KEY_EXCHANGE, "master_secret: {0}",
                 new ByteArray(session.privateData.masterSecret));
    
    // Wipe out the preMasterSecret.
    for (int i = 0; i < preMasterSecret.length; i++)
      preMasterSecret[i] = 0;
  }
}