277. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 9/25/2018 2:13:25 PM Central Daylight Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.

277.1 Files compared

# Location File Last Modified
1 build 3.zip\build 3\MHLTH_YS_137_Source\JavaScript\resources\javaJDF-1.8.0\src\sun\security\ssl HandshakeMessage.java Mon Jan 22 14:46:54 2018 UTC
2 build 3.zip\build 3\MHLTH_YS_137_Source\JavaScript\resources\javaJDF-1.8.0\src\sun\security\ssl HandshakeMessage.java Wed Sep 12 17:54:38 2018 UTC

277.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 4 4102
Changed 3 6
Inserted 0 0
Removed 0 0

277.3 Comparison options

Whitespace
Character case Differences in character case are significant
Line endings Differences in line endings (CR and LF characters) are ignored
CR/LF characters Not shown in the comparison detail

277.4 Active regular expressions

No regular expressions were active.

277.5 Comparison detail

  1   /*
  2    * Copyrig ht (c) 199 6, 2015, O racle and/ or its aff iliates. A ll rights  reserved.
  3    * DO NOT  ALTER OR R EMOVE COPY RIGHT NOTI CES OR THI S FILE HEA DER.
  4    *
  5    * This co de is free  software;  you can r edistribut e it and/o r modify i t
  6    * under t he terms o f the GNU  General Pu blic Licen se version  2 only, a s
  7    * publish ed by the  Free Softw are Founda tion.  Ora cle design ates this
  8    * particu lar file a s subject  to the "Cl asspath" e xception a s provided
  9    * by Orac le in the  LICENSE fi le that ac companied  this code.
  10    *
  11    * This co de is dist ributed in  the hope  that it wi ll be usef ul, but WI THOUT
  12    * ANY WAR RANTY; wit hout even  the implie d warranty  of MERCHA NTABILITY  or
  13    * FITNESS  FOR A PAR TICULAR PU RPOSE.  Se e the GNU  General Pu blic Licen se
  14    * version  2 for mor e details  (a copy is  included  in the LIC ENSE file  that
  15    * accompa nied this  code).
  16    *
  17    * You sho uld have r eceived a  copy of th e GNU Gene ral Public  License v ersion
  18    * 2 along  with this  work; if  not, write  to the Fr ee Softwar e Foundati on,
  19    * Inc., 5 1 Franklin  St, Fifth  Floor, Bo ston, MA 0 2110-1301  USA.
  20    *
  21    * Please  contact Or acle, 500  Oracle Par kway, Redw ood Shores , CA 94065  USA
  22    * or visi t www.orac le.com if  you need a dditional  informatio n or have  any
  23    * questio ns.
  24    */
  25  
  26   package su n.security .ssl;
  27  
  28   import jav a.io.*;
  29   import jav a.math.Big Integer;
  30   import jav a.security .*;
  31   import jav a.security .interface s.*;
  32   import jav a.security .spec.*;
  33   import jav a.security .cert.*;
  34   import jav a.security .cert.Cert ificate;
  35   import jav a.util.*;
  36   import jav a.util.con current.Co ncurrentHa shMap;
  37  
  38   import jav a.lang.ref lect.*;
  39  
  40   import jav ax.securit y.auth.x50 0.X500Prin cipal;
  41  
  42   import jav ax.crypto. KeyGenerat or;
  43   import jav ax.crypto. SecretKey;
  44   import jav ax.crypto. spec.DHPub licKeySpec ;
  45  
  46   import jav ax.net.ssl .*;
  47  
  48   import sun .security. internal.s pec.TlsPrf ParameterS pec;
  49   import sun .security. ssl.Cipher Suite.*;
  50   import sta tic sun.se curity.ssl .CipherSui te.PRF.*;
  51   import sun .security. util.KeyUt il;
  52  
  53   /**
  54    * Many da ta structu res are in volved in  the handsh ake messag es.  These
  55    * classes  are used  as structu res, with  public dat a members.   They are
  56    * not vis ible outsi de the SSL  package.
  57    *
  58    * Handsha ke message s all have  a common  header for mat, and t hey are al l
  59    * encoded  in a "han dshake dat a" SSL rec ord substr eam.  The  base class
  60    * here (H andshakeMe ssage) pro vides a co mmon frame work and r ecords the
  61    * SSL rec ord type o f the part icular han dshake mes sage.
  62    *
  63    * This fi le contain s subclass es for all  the basic  handshake  messages.
  64    * All han dshake mes sages know  how to en code and d ecode them selves on
  65    * SSL str eams; this  facilitat es using t he same co de on SSL  client and
  66    * server  sides, alt hough they  don't sen d and rece ive the sa me message s.
  67    *
  68    * Message s also kno w how to p rint thems elves, whi ch is quit e handy
  69    * for deb ugging.  T hey always  identify  their type , and can  optionally
  70    * dump al l of their  content.
  71    *
  72    * @author  David Bro wnell
  73    */
  74   public abs tract clas s Handshak eMessage {
  75  
  76       Handsh akeMessage () { }
  77  
  78       // enu m Handshak eType:
  79       static  final byt e   ht_hel lo_request  = 0;
  80       static  final byt e   ht_cli ent_hello  = 1;
  81       static  final byt e   ht_ser ver_hello  = 2;
  82  
  83       static  final byt e   ht_cer tificate =  11;
  84       static  final byt e   ht_ser ver_key_ex change = 1 2;
  85       static  final byt e   ht_cer tificate_r equest = 1 3;
  86       static  final byt e   ht_ser ver_hello_ done = 14;
  87       static  final byt e   ht_cer tificate_v erify = 15 ;
  88       static  final byt e   ht_cli ent_key_ex change = 1 6;
  89  
  90       static  final byt e   ht_fin ished = 20 ;
  91  
  92       /* Cla ss and sub class dyna mic debugg ing suppor t */
  93       public  static fi nal Debug  debug = De bug.getIns tance("ssl ");
  94  
  95       /**
  96        * Uti lity metho d to conve rt a BigIn teger to a  byte arra y in unsig ned
  97        * for mat as nee ded in the  handshake  messages.  BigIntege r uses
  98        * 2's  complemen t format,  i.e. it pr epends an  extra zero  if the MS B
  99        * is  set. We re move that.
  100        */
  101       static  byte[] to ByteArray( BigInteger  bi) {
  102           by te[] b = b i.toByteAr ray();
  103           if  ((b.lengt h > 1) &&  (b[0] == 0 )) {
  104                int n =  b.length -  1;
  105                byte[] n ewarray =  new byte[n ];
  106                System.a rraycopy(b , 1, newar ray, 0, n) ;
  107                b = newa rray;
  108           }
  109           re turn b;
  110       }
  111  
  112       /*
  113        * SSL  3.0 MAC p adding con stants.
  114        * Als o used by  Certificat eVerify an d Finished  during th e handshak e.
  115        */
  116       static  final byt e[] MD5_pa d1 = genPa d(0x36, 48 );
  117       static  final byt e[] MD5_pa d2 = genPa d(0x5c, 48 );
  118  
  119       static  final byt e[] SHA_pa d1 = genPa d(0x36, 40 );
  120       static  final byt e[] SHA_pa d2 = genPa d(0x5c, 40 );
  121  
  122       privat e static b yte[] genP ad(int b,  int count)  {
  123           by te[] paddi ng = new b yte[count] ;
  124           Ar rays.fill( padding, ( byte)b);
  125           re turn paddi ng;
  126       }
  127  
  128       /*
  129        * Wri te a hands hake messa ge on the  (handshake ) output s tream.
  130        * Thi s is just  a four byt e header f ollowed by  the data.
  131        *
  132        * NOT E that hug e messages  -- notabl y, ones wi th huge ce rt
  133        * cha ins -- are  handled c orrectly.
  134        */
  135       final  void write (Handshake OutStream  s) throws  IOExceptio n {
  136           in t len = me ssageLengt h();
  137           if  (len >= R ecord.OVER FLOW_OF_IN T24) {
  138                throw ne w SSLExcep tion("Hand shake mess age too bi g"
  139                    + ",  type = "  + messageT ype() + ",  len = " +  len);
  140           }
  141           s. write(mess ageType()) ;
  142           s. putInt24(l en);
  143           se nd(s);
  144       }
  145  
  146       /*
  147        * Sub classes im plement th ese method s so those  kinds of
  148        * mes sages can  be emitted .  Base cl ass delega tes to sub class.
  149        */
  150       abstra ct int  me ssageType( );
  151       abstra ct int  me ssageLengt h();
  152       abstra ct void se nd(Handsha keOutStrea m s) throw s IOExcept ion;
  153  
  154       /*
  155        * Wri te a descr iptive mes sage on th e output s tream; for  debugging .
  156        */
  157       abstra ct void pr int(PrintS tream p) t hrows IOEx ception;
  158  
  159   //
  160   // NOTE:   the rest o f these cl asses are  nested wit hin this o ne, and ar e
  161   // importe d by other  classes i n this pac kage.  The re are a f ew other
  162   // handsha ke message  classes,  not neatly  nested he re because  of curren t
  163   // licensi ng require ment for n ative (RSA ) methods.   They bel ong here,
  164   // but tho se native  methods co mplicate t hings a lo t!
  165   //
  166  
  167  
  168   /*
  169    * HelloRe quest ...  SERVER -->  CLIENT
  170    *
  171    * Server  can ask th e client t o initiate  a new han dshake, e. g. to chan ge
  172    * session  parameter s after a  connection  has been  (re)establ ished.
  173    */
  174   static fin al class H elloReques t extends  HandshakeM essage {
  175       @Overr ide
  176       int me ssageType( ) { return  ht_hello_ request; }
  177  
  178       HelloR equest() {  }
  179  
  180       HelloR equest(Han dshakeInSt ream in) t hrows IOEx ception
  181       {
  182           //  nothing i n this mes sage
  183       }
  184  
  185       @Overr ide
  186       int me ssageLengt h() { retu rn 0; }
  187  
  188       @Overr ide
  189       void s end(Handsh akeOutStre am out) th rows IOExc eption
  190       {
  191           //  nothing i n this mes saage
  192       }
  193  
  194       @Overr ide
  195       void p rint(Print Stream out ) throws I OException
  196       {
  197           ou t.println( "*** Hello Request (e mpty)");
  198       }
  199  
  200   }
  201  
  202  
  203   /*
  204    * ClientH ello ... C LIENT -->  SERVER
  205    *
  206    * Client  initiates  handshake  by telling  server wh at it want s, and wha t it
  207    * can sup port (prio ritized by  what's fi rst in the  ciphe sui te list).
  208    *
  209    * By RFC2 246:7.4.1. 2 it's exp licitly an ticipated  that this  message
  210    * will ha ve more da ta added a t the end  ... e.g. w hat CAs th e client t rusts.
  211    * Until w e know how  to parse  it, we wil l just rea d what we  know
  212    * about,  and let ou r caller h andle the  jumps over  unknown d ata.
  213    */
  214   static fin al class C lientHello  extends H andshakeMe ssage {
  215  
  216       Protoc olVersion      protoc olVersion;
  217       Random Cookie         clnt_r andom;
  218       Sessio nId            sessio nId;
  219       privat e CipherSu iteList     cipherSui tes;
  220       byte[]                compre ssion_meth ods;
  221  
  222       HelloE xtensions  extensions  = new Hel loExtensio ns();
  223  
  224       privat e final st atic byte[ ]  NULL_CO MPRESSION  = new byte [] {0};
  225  
  226       Client Hello(Secu reRandom g enerator,  ProtocolVe rsion prot ocolVersio n,
  227                SessionI d sessionI d, CipherS uiteList c ipherSuite s) {
  228  
  229           th is.protoco lVersion =  protocolV ersion;
  230           th is.session Id = sessi onId;
  231           th is.cipherS uites = ci pherSuites ;
  232  
  233           cl nt_random  = new Rand omCookie(g enerator);
  234           co mpression_ methods =  NULL_COMPR ESSION;
  235       }
  236  
  237       Client Hello(Hand shakeInStr eam s, int  messageLe ngth) thro ws IOExcep tion {
  238           pr otocolVers ion = Prot ocolVersio n.valueOf( s.getInt8( ), s.getIn t8());
  239           cl nt_random  = new Rand omCookie(s );
  240           se ssionId =  new Sessio nId(s.getB ytes8());
  241           se ssionId.ch eckLength( protocolVe rsion);
  242           ci pherSuites  = new Cip herSuiteLi st(s);
  243           co mpression_ methods =  s.getBytes 8();
  244           if  (messageL ength() !=  messageLe ngth) {
  245                extensio ns = new H elloExtens ions(s);
  246           }
  247       }
  248  
  249       Cipher SuiteList  getCipherS uites() {
  250           re turn ciphe rSuites;
  251       }
  252  
  253       // add  renegotia tion_info  extension
  254       void a ddRenegoti ationInfoE xtension(b yte[] clie ntVerifyDa ta) {
  255           He lloExtensi on renegot iationInfo  = new Ren egotiation InfoExtens ion(
  256                         clientVeri fyData, ne w byte[0]) ;
  257           ex tensions.a dd(renegot iationInfo );
  258       }
  259  
  260       // add  server_na me extensi on
  261       void a ddSNIExten sion(List< SNIServerN ame> serve rNames) {
  262           tr y {
  263                extensio ns.add(new  ServerNam eExtension (serverNam es));
  264           }  catch (IOE xception i oe) {
  265                // ignor e the exce ption and  return
  266           }
  267       }
  268  
  269       // add  signature _algorithm  extension
  270       void a ddSignatur eAlgorithm sExtension (
  271                Collecti on<Signatu reAndHashA lgorithm>  algorithms ) {
  272           He lloExtensi on signatu reAlgorith m =
  273                    new  SignatureA lgorithmsE xtension(a lgorithms) ;
  274           ex tensions.a dd(signatu reAlgorith m);
  275       }
  276  
  277       void a ddExtended MasterSecr etExtensio n() {
  278           ex tensions.a dd(new Ext endedMaste rSecretExt ension());
  279       }
  280  
  281       @Overr ide
  282       int me ssageType( ) { return  ht_client _hello; }
  283  
  284       @Overr ide
  285       int me ssageLengt h() {
  286           /*
  287            *  Add fixed  size part s of each  field...
  288            *  version +  random +  session +  cipher + c ompress
  289            * /
  290           re turn (2 +  32 + 1 + 2  + 1
  291                + sessio nId.length ()                 /*  ... + var iable part s */
  292                + (ciphe rSuites.si ze() * 2)
  293                + compre ssion_meth ods.length )
  294                + extens ions.lengt h();
  295       }
  296  
  297       @Overr ide
  298       void s end(Handsh akeOutStre am s) thro ws IOExcep tion {
  299           s. putInt8(pr otocolVers ion.major) ;
  300           s. putInt8(pr otocolVers ion.minor) ;
  301           cl nt_random. send(s);
  302           s. putBytes8( sessionId. getId());
  303           ci pherSuites .send(s);
  304           s. putBytes8( compressio n_methods) ;
  305           ex tensions.s end(s);
  306       }
  307  
  308       @Overr ide
  309       void p rint(Print Stream s)  throws IOE xception {
  310           s. println("* ** ClientH ello, " +  protocolVe rsion);
  311  
  312           if  (debug !=  null && D ebug.isOn( "verbose") ) {
  313                s.print( "RandomCoo kie:  ");
  314                clnt_ran dom.print( s);
  315  
  316                s.print( "Session I D:  ");
  317                s.printl n(sessionI d);
  318  
  319                s.printl n("Cipher  Suites: "  + cipherSu ites);
  320  
  321                Debug.pr intln(s, " Compressio n Methods" , compress ion_method s);
  322                extensio ns.print(s );
  323                s.printl n("***");
  324           }
  325       }
  326   }
  327  
  328   /*
  329    * ServerH ello ... S ERVER -->  CLIENT
  330    *
  331    * Server  chooses pr otocol opt ions from  among thos e it suppo rts and th e
  332    * client  supports.   Then it s ends the b asic sessi on descrip tive param eters
  333    * back to  the clien t.
  334    */
  335   static fin al
  336   class Serv erHello ex tends Hand shakeMessa ge
  337   {
  338       @Overr ide
  339       int me ssageType( ) { return  ht_server _hello; }
  340  
  341       Protoc olVersion      protoc olVersion;
  342       Random Cookie         svr_ra ndom;
  343       Sessio nId            sessio nId;
  344       Cipher Suite          cipher Suite;
  345       byte                  compre ssion_meth od;
  346       HelloE xtensions  extensions  = new Hel loExtensio ns();
  347  
  348       Server Hello() {
  349           //  empty
  350       }
  351  
  352       Server Hello(Hand shakeInStr eam input,  int messa geLength)
  353                throws I OException  {
  354           pr otocolVers ion = Prot ocolVersio n.valueOf( input.getI nt8(),
  355                                                          input.getI nt8());
  356           sv r_random =  new Rando mCookie(in put);
  357           se ssionId =  new Sessio nId(input. getBytes8( ));
  358           se ssionId.ch eckLength( protocolVe rsion);
  359           ci pherSuite  = CipherSu ite.valueO f(input.ge tInt8(), i nput.getIn t8());
  360           co mpression_ method = ( byte)input .getInt8() ;
  361           if  (messageL ength() !=  messageLe ngth) {
  362                extensio ns = new H elloExtens ions(input );
  363           }
  364       }
  365  
  366       @Overr ide
  367       int me ssageLengt h()
  368       {
  369           //  almost fi xed size,  except ses sion ID an d extensio ns:
  370           //       majo r + minor  = 2
  371           //       rand om = 32
  372           //       sess ion ID len  field = 1
  373           //       ciph er suite +  compressi on = 3
  374           //       exte nsions: if  present,  2 + length  of extens ions
  375           re turn 38 +  sessionId. length() +  extension s.length() ;
  376       }
  377  
  378       @Overr ide
  379       void s end(Handsh akeOutStre am s) thro ws IOExcep tion
  380       {
  381           s. putInt8(pr otocolVers ion.major) ;
  382           s. putInt8(pr otocolVers ion.minor) ;
  383           sv r_random.s end(s);
  384           s. putBytes8( sessionId. getId());
  385           s. putInt8(ci pherSuite. id >> 8);
  386           s. putInt8(ci pherSuite. id & 0xff) ;
  387           s. putInt8(co mpression_ method);
  388           ex tensions.s end(s);
  389       }
  390  
  391       @Overr ide
  392       void p rint(Print Stream s)  throws IOE xception
  393       {
  394           s. println("* ** ServerH ello, " +  protocolVe rsion);
  395  
  396           if  (debug !=  null && D ebug.isOn( "verbose") ) {
  397                s.print( "RandomCoo kie:  ");
  398                svr_rand om.print(s );
  399  
  400                s.print( "Session I D:  ");
  401                s.printl n(sessionI d);
  402  
  403                s.printl n("Cipher  Suite: " +  cipherSui te);
  404                s.printl n("Compres sion Metho d: " + com pression_m ethod);
  405                extensio ns.print(s );
  406                s.printl n("***");
  407           }
  408       }
  409   }
  410  
  411  
  412   /*
  413    * Certifi cateMsg .. . send by  both CLIEN T and SERV ER
  414    *
  415    * Each en d of a con nection ma y need to  pass its c ertificate  chain to
  416    * the oth er end.  S uch chains  are inten ded to val idate an i dentity wi th
  417    * referen ce to some  certifyin g authorit y.  Exampl es include  companies
  418    * like Ve risign, or  financial  instituti ons.  Ther e's some c ontrol ove r
  419    * the cer tifying au thorities  which are  sent.
  420    *
  421    * NOTE: t hat these  messages m ight be hu ge, taking  many hand shake reco rds.
  422    * Up to 2 ^48 bytes  of certifi cate may b e sent, in  records o f at most  2^14
  423    * bytes e ach ... up  to 2^32 r ecords sen t on the o utput stre am.
  424    */
  425   static fin al
  426   class Cert ificateMsg  extends H andshakeMe ssage
  427   {
  428       @Overr ide
  429       int me ssageType( ) { return  ht_certif icate; }
  430  
  431       privat e X509Cert ificate[]  chain;
  432  
  433       privat e List<byt e[]> encod edChain;
  434  
  435       privat e int mess ageLength;
  436  
  437       Certif icateMsg(X 509Certifi cate[] cer ts) {
  438           ch ain = cert s;
  439       }
  440  
  441       Certif icateMsg(H andshakeIn Stream inp ut) throws  IOExcepti on {
  442           in t chainLen  = input.g etInt24();
  443           Li st<Certifi cate> v =  new ArrayL ist<>(4);
  444  
  445           Ce rtificateF actory cf  = null;
  446           wh ile (chain Len > 0) {
  447                byte[] c ert = inpu t.getBytes 24();
  448                chainLen  -= (3 + c ert.length );
  449                try {
  450                    if ( cf == null ) {
  451                         cf = Certi ficateFact ory.getIns tance("X.5 09");
  452                    }
  453                    v.ad d(cf.gener ateCertifi cate(new B yteArrayIn putStream( cert)));
  454                } catch  (Certifica teExceptio n e) {
  455                    thro w (SSLProt ocolExcept ion)new SS LProtocolE xception(
  456                         e.getMessa ge()).init Cause(e);
  457                }
  458           }
  459  
  460           ch ain = v.to Array(new  X509Certif icate[v.si ze()]);
  461       }
  462  
  463       @Overr ide
  464       int me ssageLengt h() {
  465           if  (encodedC hain == nu ll) {
  466                messageL ength = 3;
  467                encodedC hain = new  ArrayList <byte[]>(c hain.lengt h);
  468                try {
  469                    for  (X509Certi ficate cer t : chain)  {
  470                         byte[] b =  cert.getE ncoded();
  471                         encodedCha in.add(b);
  472                         messageLen gth += b.l ength + 3;
  473                    }
  474                } catch  (Certifica teEncoding Exception  e) {
  475                    enco dedChain =  null;
  476                    thro w new Runt imeExcepti on("Could  not encode  certifica tes", e);
  477                }
  478           }
  479           re turn messa geLength;
  480       }
  481  
  482       @Overr ide
  483       void s end(Handsh akeOutStre am s) thro ws IOExcep tion {
  484           s. putInt24(m essageLeng th() - 3);
  485           fo r (byte[]  b : encode dChain) {
  486                s.putByt es24(b);
  487           }
  488       }
  489  
  490       @Overr ide
  491       void p rint(Print Stream s)  throws IOE xception {
  492           s. println("* ** Certifi cate chain ");
  493  
  494           if  (chain.le ngth == 0)  {
  495                s.printl n("<Empty> ");
  496           }  else if (d ebug != nu ll && Debu g.isOn("ve rbose")) {
  497                for (int  i = 0; i  < chain.le ngth; i++)  {
  498                    s.pr intln("cha in [" + i  + "] = " +  chain[i]) ;
  499                }
  500           }
  501           s. println("* **");
  502       }
  503  
  504       X509Ce rtificate[ ] getCerti ficateChai n() {
  505           re turn chain .clone();
  506       }
  507   }
  508  
  509   /*
  510    * ServerK eyExchange  ... SERVE R --> CLIE NT
  511    *
  512    * The cip her suite  selected,  when combi ned with t he certifi cate excha nged,
  513    * implies  one of se veral diff erent kind s of key e xchange.   Most curre nt
  514    * cipher  suites req uire the s erver to s end more t han its ce rtificate.
  515    *
  516    * The pri mary excep tions are  when a ser ver sends  an encrypt ion-capabl e
  517    * RSA pub lic key in  its cert,  to be use d with RSA  (or RSA_e xport) key
  518    * exchang e; and whe n a server  sends its  Diffie-He llman cert .  Those k inds
  519    * of key  exchange d o not requ ire a Serv erKeyExcha nge messag e.
  520    *
  521    * Key exc hange can  be viewed  as having  three mode s, which a re explici t
  522    * for the  Diffie-He llman flav ors and po orly speci fied for R SA ones:
  523    *
  524    *      -  "Ephemeral " keys.  H ere, a "te mporary" k ey is allo cated by t he
  525    *         server, an d signed.   Diffie-He llman keys  signed us ing RSA or
  526    *         DSS are ep hemeral (D HE flavor) .  RSA key s get used  to do the  same
  527    *         thing, to  cut the ke y size dow n to 512 b its (expor t restrict ions)
  528    *         or for sig ning-only  RSA certif icates.
  529    *
  530    *      -  Anonymity.   Here no  server cer tificate i s sent, on ly the pub lic
  531    *         key of the  server.   This case  is subject  to man-in -the-middl e
  532    *         attacks.   This can b e done wit h Diffie-H ellman key s (DH_anon ) or
  533    *         with RSA k eys, but i s only use d in SSLv3  for DH_an on.
  534    *
  535    *      -  "Normal" c ase.  Here  a server  certificat e is sent,  and the p ublic
  536    *          key there  is used di rectly in  exchanging  the prema ster  PW      .
  537    *         For exampl e, Diffie- Hellman "D H" flavor,  and any R SA flavor  with
  538    *         only 512 b it keys.
  539    *
  540    * If a se rver certi ficate is  sent, ther e is no an onymity.   However,
  541    * when a  certificat e is sent,  ephemeral  keys may  still be u sed to
  542    * exchang e the prem aster  PW        That's how  RSA_EXPOR T often wo rks,
  543    * as well  as how th e DHE_* fl avors work .
  544    */
  545   static abs tract clas s ServerKe yExchange  extends Ha ndshakeMes sage
  546   {
  547       @Overr ide
  548       int me ssageType( ) { return  ht_server _key_excha nge; }
  549   }
  550  
  551  
  552   /*
  553    * Using R SA for Key  Exchange:   exchange  a session  key that' s not as b ig
  554    * as the  signing-on ly key.  U sed for ex port appli cations, s ince expor ted
  555    * RSA enc ryption ke ys can't b e bigger t han 512 by tes.
  556    *
  557    * This is  never use d when key s are 512  bits or sm aller, and  isn't use d
  558    * on "US  Domestic"  ciphers in  any case.
  559    */
  560   static fin al
  561   class RSA_ ServerKeyE xchange ex tends Serv erKeyExcha nge
  562   {
  563       privat e byte rsa _modulus[] ;     // 1  to 2^16 -  1 bytes
  564       privat e byte rsa _exponent[ ];    // 1  to 2^16 -  1 bytes
  565  
  566       privat e Signatur e signatur e;
  567       privat e byte[] s ignatureBy tes;
  568  
  569       /*
  570        * Has h the nonc es and the  ephemeral  RSA publi c key.
  571        */
  572       privat e void upd ateSignatu re(byte cl ntNonce[],  byte svrN once[])
  573                throws S ignatureEx ception {
  574           in t tmp;
  575  
  576           si gnature.up date(clntN once);
  577           si gnature.up date(svrNo nce);
  578  
  579           tm p = rsa_mo dulus.leng th;
  580           si gnature.up date((byte )(tmp >> 8 ));
  581           si gnature.up date((byte )(tmp & 0x 0ff));
  582           si gnature.up date(rsa_m odulus);
  583  
  584           tm p = rsa_ex ponent.len gth;
  585           si gnature.up date((byte )(tmp >> 8 ));
  586           si gnature.up date((byte )(tmp & 0x 0ff));
  587           si gnature.up date(rsa_e xponent);
  588       }
  589  
  590  
  591       /*
  592        * Con struct an  RSA server  key excha nge messag e, using d ata
  593        * kno wn _only_  to the ser ver.
  594        *
  595        * The  client kn ows the pu blic key c orrespondi ng to this  private
  596        * key , from the  Certifica te message  sent prev iously.  T o comply
  597        * wit h US expor t regulati ons we use  short RSA  keys ...  either
  598        * lon g term one s in the s erver's X5 09 cert, o r else eph emeral
  599        * one s sent usi ng this me ssage.
  600        */
  601       RSA_Se rverKeyExc hange(Publ icKey ephe meralKey,  PrivateKey  privateKe y,
  602                RandomCo okie clntN once, Rand omCookie s vrNonce, S ecureRando m sr)
  603                throws G eneralSecu rityExcept ion {
  604           RS APublicKey Spec rsaKe y = JsseJc e.getRSAPu blicKeySpe c(ephemera lKey);
  605           rs a_modulus  = toByteAr ray(rsaKey .getModulu s());
  606           rs a_exponent  = toByteA rray(rsaKe y.getPubli cExponent( ));
  607           si gnature =  RSASignatu re.getInst ance();
  608           si gnature.in itSign(pri vateKey, s r);
  609           up dateSignat ure(clntNo nce.random _bytes, sv rNonce.ran dom_bytes) ;
  610           si gnatureByt es = signa ture.sign( );
  611       }
  612  
  613  
  614       /*
  615        * Par se an RSA  server key  exchange  message, u sing data  known
  616        * to  the client  (and, in  some situa tions, eav esdroppers ).
  617        */
  618       RSA_Se rverKeyExc hange(Hand shakeInStr eam input)
  619                throws I OException , NoSuchAl gorithmExc eption {
  620           si gnature =  RSASignatu re.getInst ance();
  621           rs a_modulus  = input.ge tBytes16() ;
  622           rs a_exponent  = input.g etBytes16( );
  623           si gnatureByt es = input .getBytes1 6();
  624       }
  625  
  626       /*
  627        * Get  the ephem eral RSA p ublic key  that will  be used in  this
  628        * SSL  connectio n.
  629        */
  630       Public Key getPub licKey() {
  631           tr y {
  632                KeyFacto ry kfac =  JsseJce.ge tKeyFactor y("RSA");
  633                // modul us and exp onent are  always pos itive
  634                RSAPubli cKeySpec k spec = new  RSAPublic KeySpec(
  635                    new  BigInteger (1, rsa_mo dulus),
  636                    new  BigInteger (1, rsa_ex ponent));
  637                return k fac.genera tePublic(k spec);
  638           }  catch (Exc eption e)  {
  639                throw ne w RuntimeE xception(e );
  640           }
  641       }
  642  
  643       /*
  644        * Ver ify the si gned tempo rary key u sing the h ashes comp uted
  645        * fro m it and t he two non ces.  This  is called  by client s
  646        * wit h "exporta ble" RSA f lavors.
  647        */
  648       boolea n verify(P ublicKey c ertifiedKe y, RandomC ookie clnt Nonce,
  649                RandomCo okie svrNo nce) throw s GeneralS ecurityExc eption {
  650           si gnature.in itVerify(c ertifiedKe y);
  651           up dateSignat ure(clntNo nce.random _bytes, sv rNonce.ran dom_bytes) ;
  652           re turn signa ture.verif y(signatur eBytes);
  653       }
  654  
  655       @Overr ide
  656       int me ssageLengt h() {
  657           re turn 6 + r sa_modulus .length +  rsa_expone nt.length
  658                   + sig natureByte s.length;
  659       }
  660  
  661       @Overr ide
  662       void s end(Handsh akeOutStre am s) thro ws IOExcep tion {
  663           s. putBytes16 (rsa_modul us);
  664           s. putBytes16 (rsa_expon ent);
  665           s. putBytes16 (signature Bytes);
  666       }
  667  
  668       @Overr ide
  669       void p rint(Print Stream s)  throws IOE xception {
  670           s. println("* ** RSA Ser verKeyExch ange");
  671  
  672           if  (debug !=  null && D ebug.isOn( "verbose") ) {
  673                Debug.pr intln(s, " RSA Modulu s", rsa_mo dulus);
  674                Debug.pr intln(s, " RSA Public  Exponent" , rsa_expo nent);
  675           }
  676       }
  677   }
  678  
  679  
  680   /*
  681    * Using D iffie-Hell man algori thm for ke y exchange .  All we  really nee d to
  682    * do is s ecurely ge t Diffie-H ellman key s (using t he same P,  G paramet ers)
  683    * to our  peer, then  we automa tically ha ve a share PW        without ne ed
  684    * to exch ange any m ore data.   (D-H only  solutions , such as  SKIP, coul d
  685    * elimina te key exc hange nego tiations a nd get fas ter connec tion setup .
  686    * But the y still ne ed a signa ture algor ithm like  DSS/DSA to  support t he
  687    * trusted  distribut ion of key s without  relying on  unscalabl e physical
  688    * key dis tribution  systems.)
  689    *
  690    * This cl ass suppor ts several  DH-based  key exchan ge algorit hms, thoug h
  691    * perhaps  eventuall y each des erves its  own class.   Notably,  this has
  692    * basic s upport for  DH_anon a nd its DHE _DSS and D HE_RSA sig ned varian ts.
  693    */
  694   static fin al
  695   class DH_S erverKeyEx change ext ends Serve rKeyExchan ge
  696   {
  697       // Fix  message e ncoding, s ee 4348279
  698       privat e final st atic boole an dhKeyEx changeFix  =
  699           De bug.getBoo leanProper ty("com.su n.net.ssl. dhKeyExcha ngeFix", t rue);
  700  
  701       privat e byte                  dh_p [];         //  1 to 2^16  - 1 bytes
  702       privat e byte                  dh_g [];         //  1 to 2^16  - 1 bytes
  703       privat e byte                  dh_Ys [] ;       //  1 to 2^16  - 1 bytes
  704  
  705       privat e byte                  signatur e [];
  706  
  707       // pro tocol vers ion being  establishe d using th is ServerK eyExchange  message
  708       Protoc olVersion  protocolVe rsion;
  709  
  710       // the  preferabl e signatur e algorith m used by  this Serve rKeyExchan ge message
  711       privat e Signatur eAndHashAl gorithm pr eferableSi gnatureAlg orithm;
  712  
  713       /*
  714        * Con struct fro m initiali zed DH key  object, f or DH_anon
  715        * key  exchange.
  716        */
  717       DH_Ser verKeyExch ange(DHCry pt obj, Pr otocolVers ion protoc olVersion)  {
  718           th is.protoco lVersion =  protocolV ersion;
  719           th is.prefera bleSignatu reAlgorith m = null;
  720  
  721           //  The DH ke y has been  validated  in the co nstructor  of DHCrypt .
  722           se tValues(ob j);
  723           si gnature =  null;
  724       }
  725  
  726       /*
  727        * Con struct fro m initiali zed DH key  object an d the key  associated
  728        * wit h the cert  chain whi ch was sen t ... for  DHE_DSS an d DHE_RSA
  729        * key  exchange.   (Constru ctor calle d by serve r.)
  730        */
  731       DH_Ser verKeyExch ange(DHCry pt obj, Pr ivateKey k ey, byte c lntNonce[] ,
  732                byte svr Nonce[], S ecureRando m sr,
  733                Signatur eAndHashAl gorithm si gnAlgorith m,
  734                Protocol Version pr otocolVers ion) throw s GeneralS ecurityExc eption {
  735  
  736           th is.protoco lVersion =  protocolV ersion;
  737  
  738           //  The DH ke y has been  validated  in the co nstructor  of DHCrypt .
  739           se tValues(ob j);
  740  
  741           Si gnature si g;
  742           if  (protocol Version.v  >= Protoco lVersion.T LS12.v) {
  743                this.pre ferableSig natureAlgo rithm = si gnAlgorith m;
  744                sig = Js seJce.getS ignature(s ignAlgorit hm.getAlgo rithmName( ));
  745           }  else {
  746                this.pre ferableSig natureAlgo rithm = nu ll;
  747                if (key. getAlgorit hm().equal s("DSA"))  {
  748                    sig  = JsseJce. getSignatu re(JsseJce .SIGNATURE _DSA);
  749                } else {
  750                    sig  = RSASigna ture.getIn stance();
  751                }
  752           }
  753  
  754           si g.initSign (key, sr);
  755           up dateSignat ure(sig, c lntNonce,  svrNonce);
  756           si gnature =  sig.sign() ;
  757       }
  758  
  759       /*
  760        * Con struct a D H_ServerKe yExchange  message fr om an inpu t
  761        * str eam, as if  sent from  server to  client fo r use with
  762        * DH_ anon key e xchange
  763        */
  764       DH_Ser verKeyExch ange(Hands hakeInStre am input,
  765                Protocol Version pr otocolVers ion)
  766                throws I OException , GeneralS ecurityExc eption {
  767  
  768           th is.protoco lVersion =  protocolV ersion;
  769           th is.prefera bleSignatu reAlgorith m = null;
  770  
  771           dh _p = input .getBytes1 6();
  772           dh _g = input .getBytes1 6();
  773           dh _Ys = inpu t.getBytes 16();
  774           Ke yUtil.vali date(new D HPublicKey Spec(new B igInteger( 1, dh_Ys),
  775                                                    new B igInteger( 1, dh_p),
  776                                                    new B igInteger( 1, dh_g))) ;
  777  
  778           si gnature =  null;
  779       }
  780  
  781       /*
  782        * Con struct a D H_ServerKe yExchange  message fr om an inpu t stream
  783        * and  a certifi cate, as i f sent fro m server t o client f or use wit h
  784        * DHE _DSS or DH E_RSA key  exchange.   (Called b y client.)
  785        */
  786       DH_Ser verKeyExch ange(Hands hakeInStre am input,  PublicKey  publicKey,
  787                byte cln tNonce[],  byte svrNo nce[], int  messageSi ze,
  788                Collecti on<Signatu reAndHashA lgorithm>  localSuppo rtedSignAl gs,
  789                Protocol Version pr otocolVers ion)
  790                throws I OException , GeneralS ecurityExc eption {
  791  
  792           th is.protoco lVersion =  protocolV ersion;
  793  
  794           //  read para ms: Server DHParams
  795           dh _p = input .getBytes1 6();
  796           dh _g = input .getBytes1 6();
  797           dh _Ys = inpu t.getBytes 16();
  798           Ke yUtil.vali date(new D HPublicKey Spec(new B igInteger( 1, dh_Ys),
  799                                                    new B igInteger( 1, dh_p),
  800                                                    new B igInteger( 1, dh_g))) ;
  801  
  802           //  read the  signature  and hash a lgorithm
  803           if  (protocol Version.v  >= Protoco lVersion.T LS12.v) {
  804                int hash  = input.g etInt8();          //  hash algo rithm
  805                int sign ature = in put.getInt 8();    //  signature  algorithm
  806  
  807                preferab leSignatur eAlgorithm  =
  808                    Sign atureAndHa shAlgorith m.valueOf( hash, sign ature, 0);
  809  
  810                // Is it  a local s upported s ignature a lgorithm?
  811                if (!loc alSupporte dSignAlgs. contains(
  812                         preferable SignatureA lgorithm))  {
  813                    thro w new SSLH andshakeEx ception(
  814                         "Unsupport ed Signatu reAndHashA lgorithm i n " +
  815                         "ServerKey Exchange m essage: "  +
  816                         preferable SignatureA lgorithm);
  817                }
  818           }  else {
  819                this.pre ferableSig natureAlgo rithm = nu ll;
  820           }
  821  
  822           //  read the  signature
  823           by te signatu re[];
  824           if  (dhKeyExc hangeFix)  {
  825                signatur e = input. getBytes16 ();
  826           }  else {
  827                messageS ize -= (dh _p.length  + 2);
  828                messageS ize -= (dh _g.length  + 2);
  829                messageS ize -= (dh _Ys.length  + 2);
  830  
  831                signatur e = new by te[message Size];
  832                input.re ad(signatu re);
  833           }
  834  
  835           Si gnature si g;
  836           St ring algor ithm = pub licKey.get Algorithm( );
  837           if  (protocol Version.v  >= Protoco lVersion.T LS12.v) {
  838                sig = Js seJce.getS ignature(
  839                             prefer ableSignat ureAlgorit hm.getAlgo rithmName( ));
  840           }  else {
  841                    swit ch (algori thm) {
  842                         case "DSA" :
  843                             sig =  JsseJce.ge tSignature (JsseJce.S IGNATURE_D SA);
  844                             break;
  845                         case "RSA" :
  846                             sig =  RSASignatu re.getInst ance();
  847                             break;
  848                         default:
  849                             throw  new SSLKey Exception(
  850                                 "n either an  RSA or a D SA key: "  + algorith m);
  851                    }
  852           }
  853  
  854           si g.initVeri fy(publicK ey);
  855           up dateSignat ure(sig, c lntNonce,  svrNonce);
  856  
  857           if  (sig.veri fy(signatu re) == fal se ) {
  858                throw ne w SSLKeyEx ception("S erver D-H  key verifi cation fai led");
  859           }
  860       }
  861  
  862       /* Ret urn the Di ffie-Hellm an modulus  */
  863       BigInt eger getMo dulus() {
  864           re turn new B igInteger( 1, dh_p);
  865       }
  866  
  867       /* Ret urn the Di ffie-Hellm an base/ge nerator */
  868       BigInt eger getBa se() {
  869           re turn new B igInteger( 1, dh_g);
  870       }
  871  
  872       /* Ret urn the se rver's Dif fie-Hellma n public k ey */
  873       BigInt eger getSe rverPublic Key() {
  874           re turn new B igInteger( 1, dh_Ys);
  875       }
  876  
  877       /*
  878        * Upd ate sig wi th nonces  and Diffie -Hellman p ublic key.
  879        */
  880       privat e void upd ateSignatu re(Signatu re sig, by te clntNon ce[],
  881                byte svr Nonce[]) t hrows Sign atureExcep tion {
  882           in t tmp;
  883  
  884           si g.update(c lntNonce);
  885           si g.update(s vrNonce);
  886  
  887           tm p = dh_p.l ength;
  888           si g.update(( byte)(tmp  >> 8));
  889           si g.update(( byte)(tmp  & 0x0ff));
  890           si g.update(d h_p);
  891  
  892           tm p = dh_g.l ength;
  893           si g.update(( byte)(tmp  >> 8));
  894           si g.update(( byte)(tmp  & 0x0ff));
  895           si g.update(d h_g);
  896  
  897           tm p = dh_Ys. length;
  898           si g.update(( byte)(tmp  >> 8));
  899           si g.update(( byte)(tmp  & 0x0ff));
  900           si g.update(d h_Ys);
  901       }
  902  
  903       privat e void set Values(DHC rypt obj)  {
  904           dh _p = toByt eArray(obj .getModulu s());
  905           dh _g = toByt eArray(obj .getBase() );
  906           dh _Ys = toBy teArray(ob j.getPubli cKey());
  907       }
  908  
  909       @Overr ide
  910       int me ssageLengt h() {
  911           in t temp = 6 ;   // ove rhead for  p, g, y(s)  values.
  912  
  913           te mp += dh_p .length;
  914           te mp += dh_g .length;
  915           te mp += dh_Y s.length;
  916  
  917           if  (signatur e != null)  {
  918                if (prot ocolVersio n.v >= Pro tocolVersi on.TLS12.v ) {
  919                    temp  += Signat ureAndHash Algorithm. sizeInReco rd();
  920                }
  921  
  922                temp +=  signature. length;
  923                if (dhKe yExchangeF ix) {
  924                    temp  += 2;
  925                }
  926           }
  927  
  928           re turn temp;
  929       }
  930  
  931       @Overr ide
  932       void s end(Handsh akeOutStre am s) thro ws IOExcep tion {
  933           s. putBytes16 (dh_p);
  934           s. putBytes16 (dh_g);
  935           s. putBytes16 (dh_Ys);
  936  
  937           if  (signatur e != null)  {
  938                if (prot ocolVersio n.v >= Pro tocolVersi on.TLS12.v ) {
  939                    s.pu tInt8(pref erableSign atureAlgor ithm.getHa shValue()) ;
  940                    s.pu tInt8(pref erableSign atureAlgor ithm.getSi gnatureVal ue());
  941                }
  942  
  943                if (dhKe yExchangeF ix) {
  944                    s.pu tBytes16(s ignature);
  945                } else {
  946                    s.wr ite(signat ure);
  947                }
  948           }
  949       }
  950  
  951       @Overr ide
  952       void p rint(Print Stream s)  throws IOE xception {
  953           s. println("* ** Diffie- Hellman Se rverKeyExc hange");
  954  
  955           if  (debug !=  null && D ebug.isOn( "verbose") ) {
  956                Debug.pr intln(s, " DH Modulus ", dh_p);
  957                Debug.pr intln(s, " DH Base",  dh_g);
  958                Debug.pr intln(s, " Server DH  Public Key ", dh_Ys);
  959  
  960                if (sign ature == n ull) {
  961                    s.pr intln("Ano nymous");
  962                } else {
  963                    if ( protocolVe rsion.v >=  ProtocolV ersion.TLS 12.v) {
  964                         s.println( "Signature  Algorithm  " +
  965                             prefer ableSignat ureAlgorit hm.getAlgo rithmName( ));
  966                    }
  967  
  968                    s.pr intln("Sig ned with a  DSA or RS A public k ey");
  969                }
  970           }
  971       }
  972   }
  973  
  974   /*
  975    * ECDH se rver key e xchange me ssage. Sen t by the s erver for  ECDHE and  ECDH_anon
  976    * ciphers uites to c ommunicate  its ephem eral publi c key (inc luding the
  977    * EC doma in paramet ers).
  978    *
  979    * We supp ort named  curves onl y, no expl icitly enc oded curve s.
  980    */
  981   static fin al
  982   class ECDH _ServerKey Exchange e xtends Ser verKeyExch ange {
  983  
  984       // con stants for  ECCurveTy pe
  985       privat e final st atic int C URVE_EXPLI CIT_PRIME  = 1;
  986       privat e final st atic int C URVE_EXPLI CIT_CHAR2  = 2;
  987       privat e final st atic int C URVE_NAMED _CURVE     = 3;
  988  
  989       // id  of the cur ve we are  using
  990       privat e int curv eId;
  991       // enc oded publi c point
  992       privat e byte[] p ointBytes;
  993  
  994       // sig nature byt es (or nul l if anony mous)
  995       privat e byte[] s ignatureBy tes;
  996  
  997       // pub lic key ob ject encap sulated in  this mess age
  998       privat e ECPublic Key public Key;
  999  
  1000       // pro tocol vers ion being  establishe d using th is ServerK eyExchange  message
  1001       Protoc olVersion  protocolVe rsion;
  1002  
  1003       // the  preferabl e signatur e algorith m used by  this Serve rKeyExchan ge message
  1004       privat e Signatur eAndHashAl gorithm pr eferableSi gnatureAlg orithm;
  1005  
  1006       ECDH_S erverKeyEx change(ECD HCrypt obj , PrivateK ey private Key,
  1007                byte[] c lntNonce,  byte[] svr Nonce, Sec ureRandom  sr,
  1008                Signatur eAndHashAl gorithm si gnAlgorith m,
  1009                Protocol Version pr otocolVers ion) throw s GeneralS ecurityExc eption {
  1010  
  1011           th is.protoco lVersion =  protocolV ersion;
  1012  
  1013           pu blicKey =  (ECPublicK ey)obj.get PublicKey( );
  1014           EC ParameterS pec params  = publicK ey.getPara ms();
  1015           EC Point poin t = public Key.getW() ;
  1016           po intBytes =  JsseJce.e ncodePoint (point, pa rams.getCu rve());
  1017           cu rveId = El lipticCurv esExtensio n.getCurve Index(para ms);
  1018  
  1019           if  (privateK ey == null ) {
  1020                // ECDH_ anon
  1021                return;
  1022           }
  1023  
  1024           Si gnature si g;
  1025           if  (protocol Version.v  >= Protoco lVersion.T LS12.v) {
  1026                this.pre ferableSig natureAlgo rithm = si gnAlgorith m;
  1027                sig = Js seJce.getS ignature(s ignAlgorit hm.getAlgo rithmName( ));
  1028           }  else {
  1029                sig = ge tSignature (privateKe y.getAlgor ithm());
  1030           }
  1031           si g.initSign (privateKe y, sr);
  1032  
  1033           up dateSignat ure(sig, c lntNonce,  svrNonce);
  1034           si gnatureByt es = sig.s ign();
  1035       }
  1036  
  1037       /*
  1038        * Par se an ECDH  server ke y exchange  message.
  1039        */
  1040       ECDH_S erverKeyEx change(Han dshakeInSt ream input , PublicKe y signingK ey,
  1041                byte[] c lntNonce,  byte[] svr Nonce,
  1042                Collecti on<Signatu reAndHashA lgorithm>  localSuppo rtedSignAl gs,
  1043                Protocol Version pr otocolVers ion)
  1044                throws I OException , GeneralS ecurityExc eption {
  1045  
  1046           th is.protoco lVersion =  protocolV ersion;
  1047  
  1048           //  read para ms: Server ECDHParams
  1049           in t curveTyp e = input. getInt8();
  1050           EC ParameterS pec parame ters;
  1051           //  These par sing error s should n ever occur  as we neg otiated
  1052           //  the suppo rted curve s during t he exchang e of the H ello messa ges.
  1053           if  (curveTyp e == CURVE _NAMED_CUR VE) {
  1054                curveId  = input.ge tInt16();
  1055                if (!Ell ipticCurve sExtension .isSupport ed(curveId )) {
  1056                    thro w new SSLH andshakeEx ception(
  1057                         "Unsupport ed curveId : " + curv eId);
  1058                }
  1059                String c urveOid =  EllipticCu rvesExtens ion.getCur veOid(curv eId);
  1060                if (curv eOid == nu ll) {
  1061                    thro w new SSLH andshakeEx ception(
  1062                         "Unknown n amed curve : " + curv eId);
  1063                }
  1064                paramete rs = JsseJ ce.getECPa rameterSpe c(curveOid );
  1065                if (para meters ==  null) {
  1066                    thro w new SSLH andshakeEx ception(
  1067                         "Unsupport ed curve:  " + curveO id);
  1068                }
  1069           }  else {
  1070                throw ne w SSLHands hakeExcept ion(
  1071                    "Uns upported E CCurveType : " + curv eType);
  1072           }
  1073           po intBytes =  input.get Bytes8();
  1074  
  1075           EC Point poin t = JsseJc e.decodePo int(pointB ytes, para meters.get Curve());
  1076           Ke yFactory f actory = J sseJce.get KeyFactory ("EC");
  1077           pu blicKey =  (ECPublicK ey)factory .generateP ublic(
  1078                new ECPu blicKeySpe c(point, p arameters) );
  1079  
  1080           if  (signingK ey == null ) {
  1081                // ECDH_ anon
  1082                return;
  1083           }
  1084  
  1085           //  read the  signature  and hash a lgorithm
  1086           if  (protocol Version.v  >= Protoco lVersion.T LS12.v) {
  1087                int hash  = input.g etInt8();          //  hash algo rithm
  1088                int sign ature = in put.getInt 8();    //  signature  algorithm
  1089  
  1090                preferab leSignatur eAlgorithm  =
  1091                    Sign atureAndHa shAlgorith m.valueOf( hash, sign ature, 0);
  1092  
  1093                // Is it  a local s upported s ignature a lgorithm?
  1094                if (!loc alSupporte dSignAlgs. contains(
  1095                         preferable SignatureA lgorithm))  {
  1096                    thro w new SSLH andshakeEx ception(
  1097                             "Unsup ported Sig natureAndH ashAlgorit hm in " +
  1098                             "Serve rKeyExchan ge message : " +
  1099                             prefer ableSignat ureAlgorit hm);
  1100                }
  1101           }
  1102  
  1103           //  read the  signature
  1104           si gnatureByt es = input .getBytes1 6();
  1105  
  1106           //  verify th e signatur e
  1107           Si gnature si g;
  1108           if  (protocol Version.v  >= Protoco lVersion.T LS12.v) {
  1109                sig = Js seJce.getS ignature(
  1110                             prefer ableSignat ureAlgorit hm.getAlgo rithmName( ));
  1111           }  else {
  1112                sig = ge tSignature (signingKe y.getAlgor ithm());
  1113           }
  1114           si g.initVeri fy(signing Key);
  1115  
  1116           up dateSignat ure(sig, c lntNonce,  svrNonce);
  1117  
  1118           if  (sig.veri fy(signatu reBytes) = = false )  {
  1119                throw ne w SSLKeyEx ception(
  1120                    "Inv alid signa ture on EC DH server  key exchan ge message ");
  1121           }
  1122       }
  1123  
  1124       /*
  1125        * Get  the ephem eral EC pu blic key e ncapsulate d in this  message.
  1126        */
  1127       ECPubl icKey getP ublicKey()  {
  1128           re turn publi cKey;
  1129       }
  1130  
  1131       privat e static S ignature g etSignatur e(String k eyAlgorith m)
  1132                throws N oSuchAlgor ithmExcept ion {
  1133                switch ( keyAlgorit hm) {
  1134                    case  "EC":
  1135                         return Jss eJce.getSi gnature(Js seJce.SIGN ATURE_ECDS A);
  1136                    case  "RSA":
  1137                         return RSA Signature. getInstanc e();
  1138                    defa ult:
  1139                         throw new  NoSuchAlgo rithmExcep tion(
  1140                             "neith er an RSA  or a EC ke y : " + ke yAlgorithm );
  1141                }
  1142       }
  1143  
  1144       privat e void upd ateSignatu re(Signatu re sig, by te clntNon ce[],
  1145                byte svr Nonce[]) t hrows Sign atureExcep tion {
  1146           si g.update(c lntNonce);
  1147           si g.update(s vrNonce);
  1148  
  1149           si g.update(( byte)CURVE _NAMED_CUR VE);
  1150           si g.update(( byte)(curv eId >> 8)) ;
  1151           si g.update(( byte)curve Id);
  1152           si g.update(( byte)point Bytes.leng th);
  1153           si g.update(p ointBytes) ;
  1154       }
  1155  
  1156       @Overr ide
  1157       int me ssageLengt h() {
  1158           in t sigLen =  0;
  1159           if  (signatur eBytes !=  null) {
  1160                sigLen =  2 + signa tureBytes. length;
  1161                if (prot ocolVersio n.v >= Pro tocolVersi on.TLS12.v ) {
  1162                    sigL en += Sign atureAndHa shAlgorith m.sizeInRe cord();
  1163                }
  1164           }
  1165  
  1166           re turn 4 + p ointBytes. length + s igLen;
  1167       }
  1168  
  1169       @Overr ide
  1170       void s end(Handsh akeOutStre am s) thro ws IOExcep tion {
  1171           s. putInt8(CU RVE_NAMED_ CURVE);
  1172           s. putInt16(c urveId);
  1173           s. putBytes8( pointBytes );
  1174  
  1175           if  (signatur eBytes !=  null) {
  1176                if (prot ocolVersio n.v >= Pro tocolVersi on.TLS12.v ) {
  1177                    s.pu tInt8(pref erableSign atureAlgor ithm.getHa shValue()) ;
  1178                    s.pu tInt8(pref erableSign atureAlgor ithm.getSi gnatureVal ue());
  1179                }
  1180  
  1181                s.putByt es16(signa tureBytes) ;
  1182           }
  1183       }
  1184  
  1185       @Overr ide
  1186       void p rint(Print Stream s)  throws IOE xception {
  1187           s. println("* ** ECDH Se rverKeyExc hange");
  1188  
  1189           if  (debug !=  null && D ebug.isOn( "verbose") ) {
  1190                if (sign atureBytes  == null)  {
  1191                    s.pr intln("Ano nymous");
  1192                } else {
  1193                    if ( protocolVe rsion.v >=  ProtocolV ersion.TLS 12.v) {
  1194                         s.println( "Signature  Algorithm  " +
  1195                                 pr eferableSi gnatureAlg orithm.get AlgorithmN ame());
  1196                    }
  1197                }
  1198  
  1199                s.printl n("Server  key: " + p ublicKey);
  1200           }
  1201       }
  1202   }
  1203  
  1204   static fin al class D istinguish edName {
  1205  
  1206       /*
  1207        * DER  encoded d istinguish ed name.
  1208        * TLS  requires  that its n ot longer  than 65535  bytes.
  1209        */
  1210       byte n ame[];
  1211  
  1212       Distin guishedNam e(Handshak eInStream  input) thr ows IOExce ption {
  1213           na me = input .getBytes1 6();
  1214       }
  1215  
  1216       Distin guishedNam e(X500Prin cipal dn)  {
  1217           na me = dn.ge tEncoded() ;
  1218       }
  1219  
  1220       X500Pr incipal ge tX500Princ ipal() thr ows IOExce ption {
  1221           tr y {
  1222                return n ew X500Pri ncipal(nam e);
  1223           }  catch (Ill egalArgume ntExceptio n e) {
  1224                throw (S SLProtocol Exception) new SSLPro tocolExcep tion(
  1225                    e.ge tMessage() ).initCaus e(e);
  1226           }
  1227       }
  1228  
  1229       int le ngth() {
  1230           re turn 2 + n ame.length ;
  1231       }
  1232  
  1233       void s end(Handsh akeOutStre am output)  throws IO Exception  {
  1234           ou tput.putBy tes16(name );
  1235       }
  1236  
  1237       void p rint(Print Stream out put) throw s IOExcept ion {
  1238           X5 00Principa l principa l = new X5 00Principa l(name);
  1239           ou tput.print ln("<" + p rincipal.t oString()  + ">");
  1240       }
  1241   }
  1242  
  1243   /*
  1244    * Certifi cateReques t ... SERV ER --> CLI ENT
  1245    *
  1246    * Authent icated ser vers may a sk clients  to authen ticate the mselves
  1247    * in turn , using th is message .
  1248    *
  1249    * Prior t o TLS 1.2,  the struc ture of th e message  is defined  as:
  1250    *     str uct {
  1251    *          ClientCer tificateTy pe certifi cate_types <1..2^8-1> ;
  1252    *          Distingui shedName c ertificate _authoriti es<0..2^16 -1>;
  1253    *     } C ertificate Request;
  1254    *
  1255    * In TLS  1.2, the s tructure i s changed  to:
  1256    *     str uct {
  1257    *          ClientCer tificateTy pe certifi cate_types <1..2^8-1> ;
  1258    *          Signature AndHashAlg orithm
  1259    *            support ed_signatu re_algorit hms<2^16-1 >;
  1260    *          Distingui shedName c ertificate _authoriti es<0..2^16 -1>;
  1261    *     } C ertificate Request;
  1262    *
  1263    */
  1264   static fin al
  1265   class Cert ificateReq uest exten ds Handsha keMessage
  1266   {
  1267       // enu m ClientCe rtificateT ype
  1268       static  final int    cct_rsa _sign = 1;
  1269       static  final int    cct_dss _sign = 2;
  1270       static  final int    cct_rsa _fixed_dh  = 3;
  1271       static  final int    cct_dss _fixed_dh  = 4;
  1272  
  1273       // The  existance  of these  two values  is a bug  in the SSL  specifica tion.
  1274       // The y are neve r used in  the protoc ol.
  1275       static  final int    cct_rsa _ephemeral _dh = 5;
  1276       static  final int    cct_dss _ephemeral _dh = 6;
  1277  
  1278       // Fro m RFC 4492  (ECC)
  1279       static  final int     cct_ec dsa_sign        = 64;
  1280       static  final int     cct_rs a_fixed_ec dh   = 65;
  1281       static  final int     cct_ec dsa_fixed_ ecdh = 66;
  1282  
  1283       privat e final st atic byte[ ] TYPES_NO _ECC = { c ct_rsa_sig n, cct_dss _sign };
  1284       privat e final st atic byte[ ] TYPES_EC C =
  1285           {  cct_rsa_si gn, cct_ds s_sign, cc t_ecdsa_si gn };
  1286  
  1287       byte                  types  [];                //  1 to 255  types
  1288       Distin guishedNam e   author ities [];          //  3 to 2^16  - 1
  1289           //  ... "3" b ecause tha t's the sm allest DER -encoded X 500 DN
  1290  
  1291       // pro tocol vers ion being  establishe d using th is Certifi cateReques t message
  1292       Protoc olVersion  protocolVe rsion;
  1293  
  1294       // sup ported_sig nature_alg orithms fo r TLS 1.2  or later
  1295       privat e Collecti on<Signatu reAndHashA lgorithm>  algorithms ;
  1296  
  1297       // len gth of sup ported_sig nature_alg orithms
  1298       privat e int algo rithmsLen;
  1299  
  1300       Certif icateReque st(X509Cer tificate c a[], KeyEx change key Exchange,
  1301                Collecti on<Signatu reAndHashA lgorithm>  signAlgs,
  1302                Protocol Version pr otocolVers ion) throw s IOExcept ion {
  1303  
  1304           th is.protoco lVersion =  protocolV ersion;
  1305  
  1306           //  always us e X500Prin cipal
  1307           au thorities  = new Dist inguishedN ame[ca.len gth];
  1308           fo r (int i =  0; i < ca .length; i ++) {
  1309                X500Prin cipal x500 Principal  = ca[i].ge tSubjectX5 00Principa l();
  1310                authorit ies[i] = n ew Disting uishedName (x500Princ ipal);
  1311           }
  1312           //  we suppor t RSA, DSS , and ECDS A client a uthenticat ion and th ey
  1313           //  can be us ed with al l ciphersu ites. If t his change s, the cod e
  1314           //  needs to  be adapted  to take k eyExchange  into acco unt.
  1315           //  We only r equest ECD SA client  auth if we  have ECC  crypto ava ilable.
  1316           th is.types =  JsseJce.i sEcAvailab le() ? TYP ES_ECC : T YPES_NO_EC C;
  1317  
  1318           //  Use suppo rted_signa ture_algor ithms for  TLS 1.2 or  later.
  1319           if  (protocol Version.v  >= Protoco lVersion.T LS12.v) {
  1320                if (sign Algs == nu ll || sign Algs.isEmp ty()) {
  1321                    thro w new SSLP rotocolExc eption(
  1322                             "No su pported si gnature al gorithms") ;
  1323                }
  1324  
  1325                algorith ms = new A rrayList<S ignatureAn dHashAlgor ithm>(sign Algs);
  1326                algorith msLen =
  1327                    Sign atureAndHa shAlgorith m.sizeInRe cord() * a lgorithms. size();
  1328           }  else {
  1329                algorith ms = new A rrayList<S ignatureAn dHashAlgor ithm>();
  1330                algorith msLen = 0;
  1331           }
  1332       }
  1333  
  1334       Certif icateReque st(Handsha keInStream  input,
  1335                Protocol Version pr otocolVers ion) throw s IOExcept ion {
  1336  
  1337           th is.protoco lVersion =  protocolV ersion;
  1338  
  1339           //  Read the  certificat e_types.
  1340           ty pes = inpu t.getBytes 8();
  1341  
  1342           //  Read the  supported_ signature_ algorithms  for TLS 1 .2 or late r.
  1343           if  (protocol Version.v  >= Protoco lVersion.T LS12.v) {
  1344                algorith msLen = in put.getInt 16();
  1345                if (algo rithmsLen  < 2) {
  1346                    thro w new SSLP rotocolExc eption(
  1347                         "Invalid s upported_s ignature_a lgorithms  field: " +
  1348                         algorithms Len);
  1349                }
  1350  
  1351                algorith ms = new A rrayList<S ignatureAn dHashAlgor ithm>();
  1352                int rema ins = algo rithmsLen;
  1353                int sequ ence = 0;
  1354                while (r emains > 1 ) {    //  needs at l east two b ytes
  1355                    int  hash = inp ut.getInt8 ();          // hash  algorithm
  1356                    int  signature  = input.ge tInt8();     // signa ture algor ithm
  1357  
  1358                    Sign atureAndHa shAlgorith m algorith m =
  1359                         SignatureA ndHashAlgo rithm.valu eOf(hash,  signature,
  1360                                                                         ++sequ ence);
  1361                    algo rithms.add (algorithm );
  1362                    rema ins -= 2;   // one by te for has h, one byt e for sign ature
  1363                }
  1364  
  1365                if (rema ins != 0)  {
  1366                    thro w new SSLP rotocolExc eption(
  1367                         "Invalid s upported_s ignature_a lgorithms  field. rem ains: " +
  1368                         remains);
  1369                }
  1370           }  else {
  1371                algorith ms = new A rrayList<S ignatureAn dHashAlgor ithm>();
  1372                algorith msLen = 0;
  1373           }
  1374  
  1375           //  read the  certificat e_authorit ies
  1376           in t len = in put.getInt 16();
  1377           Ar rayList<Di stinguishe dName> v =  new Array List<>();
  1378           wh ile (len > = 3) {
  1379                Distingu ishedName  dn = new D istinguish edName(inp ut);
  1380                v.add(dn );
  1381                len -= d n.length() ;
  1382           }
  1383  
  1384           if  (len != 0 ) {
  1385                throw ne w SSLProto colExcepti on(
  1386                    "Bad  Certifica teRequest  DN length:  " + len);
  1387           }
  1388  
  1389           au thorities  = v.toArra y(new Dist inguishedN ame[v.size ()]);
  1390       }
  1391  
  1392       X500Pr incipal[]  getAuthori ties() thr ows IOExce ption {
  1393           X5 00Principa l[] ret =  new X500Pr incipal[au thorities. length];
  1394           fo r (int i =  0; i < au thorities. length; i+ +) {
  1395                ret[i] =  authoriti es[i].getX 500Princip al();
  1396           }
  1397           re turn ret;
  1398       }
  1399  
  1400       Collec tion<Signa tureAndHas hAlgorithm > getSignA lgorithms( ) {
  1401           re turn algor ithms;
  1402       }
  1403  
  1404       @Overr ide
  1405       int me ssageType( ) {
  1406           re turn ht_ce rtificate_ request;
  1407       }
  1408  
  1409       @Overr ide
  1410       int me ssageLengt h() {
  1411           in t len = 1  + types.le ngth + 2;
  1412  
  1413           if  (protocol Version.v  >= Protoco lVersion.T LS12.v) {
  1414                len += a lgorithmsL en + 2;
  1415           }
  1416  
  1417           fo r (int i =  0; i < au thorities. length; i+ +) {
  1418                len += a uthorities [i].length ();
  1419           }
  1420  
  1421           re turn len;
  1422       }
  1423  
  1424       @Overr ide
  1425       void s end(Handsh akeOutStre am output)  throws IO Exception  {
  1426           //  put certi ficate_typ es
  1427           ou tput.putBy tes8(types );
  1428  
  1429           //  put suppo rted_signa ture_algor ithms
  1430           if  (protocol Version.v  >= Protoco lVersion.T LS12.v) {
  1431                output.p utInt16(al gorithmsLe n);
  1432                for (Sig natureAndH ashAlgorit hm algorit hm : algor ithms) {
  1433                    outp ut.putInt8 (algorithm .getHashVa lue());       // hash
  1434                    outp ut.putInt8 (algorithm .getSignat ureValue() ); // sign ature
  1435                }
  1436           }
  1437  
  1438           //  put certi ficate_aut horities
  1439           in t len = 0;
  1440           fo r (int i =  0; i < au thorities. length; i+ +) {
  1441                len += a uthorities [i].length ();
  1442           }
  1443  
  1444           ou tput.putIn t16(len);
  1445           fo r (int i =  0; i < au thorities. length; i+ +) {
  1446                authorit ies[i].sen d(output);
  1447           }
  1448       }
  1449  
  1450       @Overr ide
  1451       void p rint(Print Stream s)  throws IOE xception {
  1452           s. println("* ** Certifi cateReques t");
  1453  
  1454           if  (debug !=  null && D ebug.isOn( "verbose") ) {
  1455                s.print( "Cert Type s: ");
  1456                for (int  i = 0; i  < types.le ngth; i++)  {
  1457                    swit ch (types[ i]) {
  1458                      ca se cct_rsa _sign:
  1459                         s.print("R SA"); brea k;
  1460                      ca se cct_dss _sign:
  1461                         s.print("D SS"); brea k;
  1462                      ca se cct_rsa _fixed_dh:
  1463                         s.print("F ixed DH (R SA sig)");  break;
  1464                      ca se cct_dss _fixed_dh:
  1465                         s.print("F ixed DH (D SS sig)");  break;
  1466                      ca se cct_rsa _ephemeral _dh:
  1467                         s.print("E phemeral D H (RSA sig )"); break ;
  1468                      ca se cct_dss _ephemeral _dh:
  1469                         s.print("E phemeral D H (DSS sig )"); break ;
  1470                      ca se cct_ecd sa_sign:
  1471                         s.print("E CDSA"); br eak;
  1472                      ca se cct_rsa _fixed_ecd h:
  1473                         s.print("F ixed ECDH  (RSA sig)" ); break;
  1474                      ca se cct_ecd sa_fixed_e cdh:
  1475                         s.print("F ixed ECDH  (ECDSA sig )"); break ;
  1476                      de fault:
  1477                         s.print("T ype-" + (t ypes[i] &  0xff)); br eak;
  1478                    }
  1479                    if ( i != types .length -  1) {
  1480                         s.print(",  ");
  1481                    }
  1482                }
  1483                s.printl n();
  1484  
  1485                if (prot ocolVersio n.v >= Pro tocolVersi on.TLS12.v ) {
  1486                    Stri ngBuffer b uffer = ne w StringBu ffer();
  1487                    bool ean opened  = false;
  1488                    for  (Signature AndHashAlg orithm sig nAlg : alg orithms) {
  1489                         if (opened ) {
  1490                             buffer .append(",  " + signA lg.getAlgo rithmName( ));
  1491                         } else {
  1492                             buffer .append(si gnAlg.getA lgorithmNa me());
  1493                             opened  = true;
  1494                         }
  1495                    }
  1496                    s.pr intln("Sup ported Sig nature Alg orithms: "  + buffer) ;
  1497                }
  1498  
  1499                s.printl n("Cert Au thorities: ");
  1500                if (auth orities.le ngth == 0)  {
  1501                    s.pr intln("<Em pty>");
  1502                } else {
  1503                    for  (int i = 0 ; i < auth orities.le ngth; i++)  {
  1504                         authoritie s[i].print (s);
  1505                    }
  1506                }
  1507           }
  1508       }
  1509   }
  1510  
  1511  
  1512   /*
  1513    * ServerH elloDone . .. SERVER  --> CLIENT
  1514    *
  1515    * When se rver's don e sending  its messag es in resp onse to th e client's
  1516    * "hello"  (e.g. its  own hello , certific ate, key e xchange me ssage, per haps
  1517    * client  certificat e request)  it sends  this messa ge to flag  that it's
  1518    * done th at part of  the hands hake.
  1519    */
  1520   static fin al
  1521   class Serv erHelloDon e extends  HandshakeM essage
  1522   {
  1523       @Overr ide
  1524       int me ssageType( ) { return  ht_server _hello_don e; }
  1525  
  1526       Server HelloDone( ) { }
  1527  
  1528       Server HelloDone( HandshakeI nStream in put)
  1529       {
  1530           //  nothing t o do
  1531       }
  1532  
  1533       @Overr ide
  1534       int me ssageLengt h()
  1535       {
  1536           re turn 0;
  1537       }
  1538  
  1539       @Overr ide
  1540       void s end(Handsh akeOutStre am s) thro ws IOExcep tion
  1541       {
  1542           //  nothing t o send
  1543       }
  1544  
  1545       @Overr ide
  1546       void p rint(Print Stream s)  throws IOE xception
  1547       {
  1548           s. println("* ** ServerH elloDone") ;
  1549       }
  1550   }
  1551  
  1552  
  1553   /*
  1554    * Certifi cateVerify  ... CLIEN T --> SERV ER
  1555    *
  1556    * Sent af ter client  sends sig nature-cap able certi ficates (e .g. not
  1557    * Diffie- Hellman) t o verify.
  1558    */
  1559   static fin al class C ertificate Verify ext ends Hands hakeMessag e {
  1560  
  1561       // the  signature  bytes
  1562       privat e byte[] s ignature;
  1563  
  1564       // pro tocol vers ion being  establishe d using th is Certifi cateVerify  message
  1565       Protoc olVersion  protocolVe rsion;
  1566  
  1567       // the  preferabl e signatur e algorith m used by  this Certi ficateVeri fy message
  1568       privat e Signatur eAndHashAl gorithm pr eferableSi gnatureAlg orithm = n ull;
  1569  
  1570       /*
  1571        * Cre ate an RSA  or DSA si gned certi ficate ver ify messag e.
  1572        */
  1573       Certif icateVerif y(Protocol Version pr otocolVers ion,
  1574                Handshak eHash hand shakeHash,  PrivateKe y privateK ey,
  1575                SecretKe y masterSe cret, Secu reRandom s r,
  1576                Signatur eAndHashAl gorithm si gnAlgorith m)
  1577                throws G eneralSecu rityExcept ion {
  1578  
  1579           th is.protoco lVersion =  protocolV ersion;
  1580  
  1581           St ring algor ithm = pri vateKey.ge tAlgorithm ();
  1582           Si gnature si g = null;
  1583           if  (protocol Version.v  >= Protoco lVersion.T LS12.v) {
  1584                this.pre ferableSig natureAlgo rithm = si gnAlgorith m;
  1585                sig = Js seJce.getS ignature(s ignAlgorit hm.getAlgo rithmName( ));
  1586           }  else {
  1587                sig = ge tSignature (protocolV ersion, al gorithm);
  1588           }
  1589           si g.initSign (privateKe y, sr);
  1590           up dateSignat ure(sig, p rotocolVer sion, hand shakeHash,  algorithm ,
  1591                             master Secret);
  1592           si gnature =  sig.sign() ;
  1593       }
  1594  
  1595       //
  1596       // Unm arshal the  signed da ta from th e input st ream.
  1597       //
  1598       Certif icateVerif y(Handshak eInStream  input,
  1599                Collecti on<Signatu reAndHashA lgorithm>  localSuppo rtedSignAl gs,
  1600                Protocol Version pr otocolVers ion) throw s IOExcept ion  {
  1601  
  1602           th is.protoco lVersion =  protocolV ersion;
  1603  
  1604           //  read the  signature  and hash a lgorithm
  1605           if  (protocol Version.v  >= Protoco lVersion.T LS12.v) {
  1606                int hash Alg = inpu t.getInt8( );          // hash a lgorithm
  1607                int sign Alg = inpu t.getInt8( );          // signat ure algori thm
  1608  
  1609                preferab leSignatur eAlgorithm  =
  1610                    Sign atureAndHa shAlgorith m.valueOf( hashAlg, s ignAlg, 0) ;
  1611  
  1612                // Is it  a local s upported s ignature a lgorithm?
  1613                if (!loc alSupporte dSignAlgs. contains(
  1614                         preferable SignatureA lgorithm))  {
  1615                    thro w new SSLH andshakeEx ception(
  1616                         "Unsupport ed Signatu reAndHashA lgorithm i n " +
  1617                         "Certifica teVerify m essage: "  + preferab leSignatur eAlgorithm );
  1618                }
  1619           }
  1620  
  1621           //  read the  signature
  1622           si gnature =  input.getB ytes16();
  1623       }
  1624  
  1625       /*
  1626        * Get  the prefe rable sign ature algo rithm used  by this m essage
  1627        */
  1628       Signat ureAndHash Algorithm  getPrefera bleSignatu reAlgorith m() {
  1629           re turn prefe rableSigna tureAlgori thm;
  1630       }
  1631  
  1632       /*
  1633        * Ver ify a cert ificate ve rify messa ge. Return  the resul t of verif ication,
  1634        * if  there is a  problem t hrow a Gen eralSecuri tyExceptio n.
  1635        */
  1636       boolea n verify(P rotocolVer sion proto colVersion ,
  1637                Handshak eHash hand shakeHash,  PublicKey  publicKey ,
  1638                SecretKe y masterSe cret) thro ws General SecurityEx ception {
  1639           St ring algor ithm = pub licKey.get Algorithm( );
  1640           Si gnature si g = null;
  1641           if  (protocol Version.v  >= Protoco lVersion.T LS12.v) {
  1642                sig = Js seJce.getS ignature(
  1643                             prefer ableSignat ureAlgorit hm.getAlgo rithmName( ));
  1644           }  else {
  1645                sig = ge tSignature (protocolV ersion, al gorithm);
  1646           }
  1647           si g.initVeri fy(publicK ey);
  1648           up dateSignat ure(sig, p rotocolVer sion, hand shakeHash,  algorithm ,
  1649                             master Secret);
  1650           re turn sig.v erify(sign ature);
  1651       }
  1652  
  1653       /*
  1654        * Get  the Signa ture objec t appropri ate for ve rification  using the
  1655        * giv en signatu re algorit hm and pro tocol vers ion.
  1656        */
  1657       privat e static S ignature g etSignatur e(Protocol Version pr otocolVers ion,
  1658                String a lgorithm)  throws Gen eralSecuri tyExceptio n {
  1659                switch ( algorithm)  {
  1660                    case  "RSA":
  1661                         return RSA Signature. getInterna lInstance( );
  1662                    case  "DSA":
  1663                         return Jss eJce.getSi gnature(Js seJce.SIGN ATURE_RAWD SA);
  1664                    case  "EC":
  1665                         return Jss eJce.getSi gnature(Js seJce.SIGN ATURE_RAWE CDSA);
  1666                    defa ult:
  1667                         throw new  SignatureE xception(" Unrecogniz ed algorit hm: "
  1668                             + algo rithm);
  1669                }
  1670       }
  1671  
  1672       /*
  1673        * Upd ate the Si gnature wi th the dat a appropri ate for th e given
  1674        * sig nature alg orithm and  protocol  version so  that the  object is
  1675        * rea dy for sig ning or ve rifying.
  1676        */
  1677       privat e static v oid update Signature( Signature  sig,
  1678                Protocol Version pr otocolVers ion,
  1679                Handshak eHash hand shakeHash,  String al gorithm, S ecretKey m asterKey)
  1680                throws S ignatureEx ception {
  1681  
  1682           if  (algorith m.equals(" RSA")) {
  1683                if (prot ocolVersio n.v < Prot ocolVersio n.TLS12.v)  { // TLS1 .1-
  1684                    Mess ageDigest  md5Clone =  handshake Hash.getMD 5Clone();
  1685                    Mess ageDigest  shaClone =  handshake Hash.getSH AClone();
  1686  
  1687                    if ( protocolVe rsion.v <  ProtocolVe rsion.TLS1 0.v) { //  SSLv3
  1688                         updateDige st(md5Clon e, MD5_pad 1, MD5_pad 2, masterK ey);
  1689                         updateDige st(shaClon e, SHA_pad 1, SHA_pad 2, masterK ey);
  1690                    }
  1691  
  1692                    // T he signatu re must be  an instan ce of RSAS ignature,  need
  1693                    // t o use thes e hashes d irectly.
  1694                    RSAS ignature.s etHashes(s ig, md5Clo ne, shaClo ne);
  1695                } else {   // TLS1. 2+
  1696                    sig. update(han dshakeHash .getAllHan dshakeMess ages());
  1697                }
  1698           }  else { //  DSA, ECDSA
  1699                if (prot ocolVersio n.v < Prot ocolVersio n.TLS12.v)  { // TLS1 .1-
  1700                    Mess ageDigest  shaClone =  handshake Hash.getSH AClone();
  1701  
  1702                    if ( protocolVe rsion.v <  ProtocolVe rsion.TLS1 0.v) { //  SSLv3
  1703                         updateDige st(shaClon e, SHA_pad 1, SHA_pad 2, masterK ey);
  1704                    }
  1705  
  1706                    sig. update(sha Clone.dige st());
  1707                } else {   // TLS1. 2+
  1708                    sig. update(han dshakeHash .getAllHan dshakeMess ages());
  1709                }
  1710           }
  1711       }
  1712  
  1713       /*
  1714        * Upd ate the Me ssageDiges t for SSLv 3 certific ate verify  or finish ed
  1715        * mes sage calcu lation. Th e digest m ust alread y have bee n updated  with
  1716        * all  preceding  handshake  messages.
  1717        * Use d by the F inished cl ass as wel l.
  1718        */
  1719       privat e static v oid update Digest(Mes sageDigest  md,
  1720                byte[] p ad1, byte[ ] pad2,
  1721                SecretKe y masterSe cret) {
  1722           //  Digest th e key byte s if avail able.
  1723           //  Otherwise  (sensitiv e key), tr y digestin g the key  directly.
  1724           //  That is c urrently o nly implem ented in S unPKCS11 u sing a pri vate
  1725           //  reflectio n API, so  we avoid t hat if pos sible.
  1726           by te[] keyBy tes = "RAW ".equals(m asterSecre t.getForma t())
  1727                             ? mast erSecret.g etEncoded( ) : null;
  1728           if  (keyBytes  != null)  {
  1729                md.updat e(keyBytes );
  1730           }  else {
  1731                digestKe y(md, mast erSecret);
  1732           }
  1733           md .update(pa d1);
  1734           by te[] temp  = md.diges t();
  1735  
  1736           if  (keyBytes  != null)  {
  1737                md.updat e(keyBytes );
  1738           }  else {
  1739                digestKe y(md, mast erSecret);
  1740           }
  1741           md .update(pa d2);
  1742           md .update(te mp);
  1743       }
  1744  
  1745       privat e final st atic Class <?> delega te;
  1746       privat e final st atic Field  spiField;
  1747  
  1748       static  {
  1749           tr y {
  1750                delegate  = Class.f orName("ja va.securit y.MessageD igest$Dele gate");
  1751                spiField  = delegat e.getDecla redField(" digestSpi" );
  1752           }  catch (Exc eption e)  {
  1753                throw ne w RuntimeE xception(" Reflection  failed",  e);
  1754           }
  1755           ma keAccessib le(spiFiel d);
  1756       }
  1757  
  1758       privat e static v oid makeAc cessible(f inal Acces sibleObjec t o) {
  1759           Ac cessContro ller.doPri vileged(ne w Privileg edAction<O bject>() {
  1760                @Overrid e
  1761                public O bject run( ) {
  1762                    o.se tAccessibl e(true);
  1763                    retu rn null;
  1764                }
  1765           }) ;
  1766       }
  1767  
  1768       // Con currentHas hMap does  not allow  null value s, use thi s marker o bject
  1769       privat e final st atic Objec t NULL_OBJ ECT = new  Object();
  1770  
  1771       // cac he Method  objects pe r Spi clas s
  1772       // Not e that thi s will pre vent the S pi classes  from bein g GC'd. We  assume
  1773       // tha t is not a  problem.
  1774       privat e final st atic Map<C lass<?>,Ob ject> meth odCache =
  1775                                               new Concur rentHashMa p<>();
  1776  
  1777       privat e static v oid digest Key(Messag eDigest md , SecretKe y key) {
  1778           tr y {
  1779                // Verif y that md  is impleme nted via M essageDige stSpi, not
  1780                // via J DK 1.1 sty le Message Digest sub classing.
  1781                if (md.g etClass()  != delegat e) {
  1782                    thro w new Exce ption("Dig est is not  a Message DigestSpi" );
  1783                }
  1784                MessageD igestSpi s pi = (Mess ageDigestS pi)spiFiel d.get(md);
  1785                Class<?>  clazz = s pi.getClas s();
  1786                Object r  = methodC ache.get(c lazz);
  1787                if (r ==  null) {
  1788                    try  {
  1789                         r = clazz. getDeclare dMethod("i mplUpdate" , SecretKe y.class);
  1790                         makeAccess ible((Meth od)r);
  1791                    } ca tch (NoSuc hMethodExc eption e)  {
  1792                         r = NULL_O BJECT;
  1793                    }
  1794                    meth odCache.pu t(clazz, r );
  1795                }
  1796                if (r ==  NULL_OBJE CT) {
  1797                    thro w new Exce ption(
  1798                         "Digest do es not sup port implU pdate(Secr etKey)");
  1799                }
  1800                Method u pdate = (M ethod)r;
  1801                update.i nvoke(spi,  key);
  1802           }  catch (Exc eption e)  {
  1803                throw ne w RuntimeE xception(
  1804                    "Cou ld not obt ain encode d key and  "
  1805                    + "M essageDige st cannot  digest key ", e);
  1806           }
  1807       }
  1808  
  1809       @Overr ide
  1810       int me ssageType( ) {
  1811           re turn ht_ce rtificate_ verify;
  1812       }
  1813  
  1814       @Overr ide
  1815       int me ssageLengt h() {
  1816           in t temp = 2 ;
  1817  
  1818           if  (protocol Version.v  >= Protoco lVersion.T LS12.v) {
  1819                temp +=  SignatureA ndHashAlgo rithm.size InRecord() ;
  1820           }
  1821  
  1822           re turn temp  + signatur e.length;
  1823       }
  1824  
  1825       @Overr ide
  1826       void s end(Handsh akeOutStre am s) thro ws IOExcep tion {
  1827           if  (protocol Version.v  >= Protoco lVersion.T LS12.v) {
  1828                s.putInt 8(preferab leSignatur eAlgorithm .getHashVa lue());
  1829                s.putInt 8(preferab leSignatur eAlgorithm .getSignat ureValue() );
  1830           }
  1831  
  1832           s. putBytes16 (signature );
  1833       }
  1834  
  1835       @Overr ide
  1836       void p rint(Print Stream s)  throws IOE xception {
  1837           s. println("* ** Certifi cateVerify ");
  1838  
  1839           if  (debug !=  null && D ebug.isOn( "verbose") ) {
  1840                if (prot ocolVersio n.v >= Pro tocolVersi on.TLS12.v ) {
  1841                    s.pr intln("Sig nature Alg orithm " +
  1842                             prefer ableSignat ureAlgorit hm.getAlgo rithmName( ));
  1843                }
  1844           }
  1845       }
  1846   }
  1847  
  1848  
  1849   /*
  1850    * FINISHE D ... sent  by both C LIENT and  SERVER
  1851    *
  1852    * This is  the FINIS HED messag e as defin ed in the  SSL and TL S protocol s.
  1853    * Both pr otocols de fine this  handshake  message sl ightly dif ferently.
  1854    * This cl ass suppor ts both fo rmats.
  1855    *
  1856    * When ha ndshaking  is finishe d, each si de sends a  "change_c ipher_spec "
  1857    * record,  then imme diately se nds a "fin ished" han dshake mes sage prepa red
  1858    * accordi ng to the  newly adop ted cipher  spec.
  1859    *
  1860    * NOTE th at until t his is sen t, no appl ication da ta may be  passed, un less
  1861    * some no n-default  cipher sui te has alr eady been  set up on  this conne ction
  1862    * connect ion (e.g.  a previous  handshake  arranged  one).
  1863    */
  1864   static fin al class F inished ex tends Hand shakeMessa ge {
  1865  
  1866       // con stant for  a Finished  message s ent by the  client
  1867       final  static int  CLIENT =  1;
  1868  
  1869       // con stant for  a Finished  message s ent by the  server
  1870       final  static int  SERVER =  2;
  1871  
  1872       // enu m Sender:   "CLNT" an d "SRVR"
  1873       privat e static f inal byte[ ] SSL_CLIE NT = { 0x4 3, 0x4C, 0 x4E, 0x54  };
  1874       privat e static f inal byte[ ] SSL_SERV ER = { 0x5 3, 0x52, 0 x56, 0x52  };
  1875  
  1876       /*
  1877        * Con tents of t he finishe d message  ("checksum "). For TL S, it
  1878        * is  12 bytes l ong, for S SLv3 36 by tes.
  1879        */
  1880       privat e byte[] v erifyData;
  1881  
  1882       /*
  1883        * Cur rent ciphe r suite we  are negot iating.  T LS 1.2 has
  1884        * cip hersuite-d efined PRF  algorithm s.
  1885        */
  1886       privat e Protocol Version pr otocolVers ion;
  1887       privat e CipherSu ite cipher Suite;
  1888  
  1889       /*
  1890        * Cre ate a fini shed messa ge to send  to the re mote peer.
  1891        */
  1892       Finish ed(Protoco lVersion p rotocolVer sion, Hand shakeHash  handshakeH ash,
  1893                int send er, Secret Key master , CipherSu ite cipher Suite) {
  1894           th is.protoco lVersion =  protocolV ersion;
  1895           th is.cipherS uite = cip herSuite;
  1896           ve rifyData =  getFinish ed(handsha keHash, se nder, mast er);
  1897       }
  1898  
  1899       /*
  1900        * Con structor t hat reads  FINISHED m essage fro m stream.
  1901        */
  1902       Finish ed(Protoco lVersion p rotocolVer sion, Hand shakeInStr eam input,
  1903                CipherSu ite cipher Suite) thr ows IOExce ption {
  1904           th is.protoco lVersion =  protocolV ersion;
  1905           th is.cipherS uite = cip herSuite;
  1906           in t msgLen =  (protocol Version.v  >= Protoco lVersion.T LS10.v) ?  12 : 36;
  1907           ve rifyData =  new byte[ msgLen];
  1908           in put.read(v erifyData) ;
  1909       }
  1910  
  1911       /*
  1912        * Ver ify that t he hashes  here are w hat would  have been  produced
  1913        * acc ording to  a given se t of input s.  This i s used to  ensure tha t
  1914        * bot h client a nd server  are fully  in sync, a nd that th e handshak e
  1915        * com putations  have been  successful .
  1916        */
  1917       boolea n verify(H andshakeHa sh handsha keHash, in t sender,  SecretKey  master) {
  1918           by te[] myFin ished = ge tFinished( handshakeH ash, sende r, master) ;
  1919           re turn Messa geDigest.i sEqual(myF inished, v erifyData) ;
  1920       }
  1921  
  1922       /*
  1923        * Per form the a ctual fini shed messa ge calcula tion.
  1924        */
  1925       privat e byte[] g etFinished (Handshake Hash hands hakeHash,
  1926                int send er, Secret Key master Key) {
  1927           by te[] sslLa bel;
  1928           St ring tlsLa bel;
  1929           if  (sender = = CLIENT)  {
  1930                sslLabel  = SSL_CLI ENT;
  1931                tlsLabel  = "client  finished" ;
  1932           }  else if (s ender == S ERVER) {
  1933                sslLabel  = SSL_SER VER;
  1934                tlsLabel  = "server  finished" ;
  1935           }  else {
  1936                throw ne w RuntimeE xception(" Invalid se nder: " +  sender);
  1937           }
  1938  
  1939           if  (protocol Version.v  >= Protoco lVersion.T LS10.v) {
  1940                // TLS 1 .0+
  1941                try {
  1942                    byte  [] seed;
  1943                    Stri ng prfAlg;
  1944                    PRF  prf;
  1945  
  1946                    // G et the Key Generator  alg and ca lculate th e seed.
  1947                    if ( protocolVe rsion.v >=  ProtocolV ersion.TLS 12.v) {
  1948                         // TLS 1.2
  1949                         seed = han dshakeHash .getFinish edHash();
  1950  
  1951                         prfAlg = " SunTls12Pr f";
  1952                         prf = ciph erSuite.pr fAlg;
  1953                    } el se {
  1954                         // TLS 1.0 /1.1
  1955                         MessageDig est md5Clo ne = hands hakeHash.g etMD5Clone ();
  1956                         MessageDig est shaClo ne = hands hakeHash.g etSHAClone ();
  1957                         seed = new  byte[36];
  1958                         md5Clone.d igest(seed , 0, 16);
  1959                         shaClone.d igest(seed , 16, 20);
  1960  
  1961                         prfAlg = " SunTlsPrf" ;
  1962                         prf = P_NO NE;
  1963                    }
  1964  
  1965                    Stri ng prfHash Alg = prf. getPRFHash Alg();
  1966                    int  prfHashLen gth = prf. getPRFHash Length();
  1967                    int  prfBlockSi ze = prf.g etPRFBlock Size();
  1968  
  1969                    /*
  1970                     * R FC 5246/7. 4.9 says t hat finish ed message s can
  1971                     * b e ciphersu ite-specif ic in both  length/PR F hash
  1972                     * a lgorithm.   If we eve r run acro ss a diffe rent
  1973                     * l ength, thi s call wil l need to  be updated .
  1974                     */
  1975                    TlsP rfParamete rSpec spec  = new Tls PrfParamet erSpec(
  1976                         masterKey,  tlsLabel,  seed, 12,
  1977                         prfHashAlg , prfHashL ength, prf BlockSize) ;
  1978  
  1979                    KeyG enerator k g = JsseJc e.getKeyGe nerator(pr fAlg);
  1980                    kg.i nit(spec);
  1981                    Secr etKey prfK ey = kg.ge nerateKey( );
  1982                    if ( "RAW".equa ls(prfKey. getFormat( )) == fals e) {
  1983                         throw new  ProviderEx ception(
  1984                             "Inval id PRF out put, forma t must be  RAW. " +
  1985                             "Forma t received : " + prfK ey.getForm at());
  1986                    }
  1987                    byte [] finishe d = prfKey .getEncode d();
  1988                    retu rn finishe d;
  1989                } catch  (GeneralSe curityExce ption e) {
  1990                    thro w new Runt imeExcepti on("PRF fa iled", e);
  1991                }
  1992           }  else {
  1993                // SSLv3
  1994                MessageD igest md5C lone = han dshakeHash .getMD5Clo ne();
  1995                MessageD igest shaC lone = han dshakeHash .getSHAClo ne();
  1996                updateDi gest(md5Cl one, sslLa bel, MD5_p ad1, MD5_p ad2, maste rKey);
  1997                updateDi gest(shaCl one, sslLa bel, SHA_p ad1, SHA_p ad2, maste rKey);
  1998                byte[] f inished =  new byte[3 6];
  1999                try {
  2000                    md5C lone.diges t(finished , 0, 16);
  2001                    shaC lone.diges t(finished , 16, 20);
  2002                } catch  (DigestExc eption e)  {
  2003                    // c annot occu r
  2004                    thro w new Runt imeExcepti on("Digest  failed",  e);
  2005                }
  2006                return f inished;
  2007           }
  2008       }
  2009  
  2010       /*
  2011        * Upd ate the Me ssageDiges t for SSLv 3 finished  message c alculation .
  2012        * The  digest mu st already  have been  updated w ith all pr eceding ha ndshake
  2013        * mes sages. Thi s operatio n is almos t identica l to the c ertificate  verify
  2014        * has h, reuse t hat code.
  2015        */
  2016       privat e static v oid update Digest(Mes sageDigest  md, byte[ ] sender,
  2017                byte[] p ad1, byte[ ] pad2, Se cretKey ma sterSecret ) {
  2018           md .update(se nder);
  2019           Ce rtificateV erify.upda teDigest(m d, pad1, p ad2, maste rSecret);
  2020       }
  2021  
  2022       // get  the verif y_data of  the finish ed message
  2023       byte[]  getVerify Data() {
  2024           re turn verif yData;
  2025       }
  2026  
  2027       @Overr ide
  2028       int me ssageType( ) { return  ht_finish ed; }
  2029  
  2030       @Overr ide
  2031       int me ssageLengt h() {
  2032           re turn verif yData.leng th;
  2033       }
  2034  
  2035       @Overr ide
  2036       void s end(Handsh akeOutStre am out) th rows IOExc eption {
  2037           ou t.write(ve rifyData);
  2038       }
  2039  
  2040       @Overr ide
  2041       void p rint(Print Stream s)  throws IOE xception {
  2042           s. println("* ** Finishe d");
  2043           if  (debug !=  null && D ebug.isOn( "verbose") ) {
  2044                Debug.pr intln(s, " verify_dat a", verify Data);
  2045                s.printl n("***");
  2046           }
  2047       }
  2048   }
  2049  
  2050   //
  2051   // END of  nested cla sses
  2052   //
  2053  
  2054   }