88. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 9/25/2018 2:13:01 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.

88.1 Files compared

# Location File Last Modified
1 build 3.zip\build 3\MHLTH_YS_137_Source\JavaScript\resources\javaJDF-1.8.0\src\com\sun\crypto\provider DESedeWrapCipher.java Mon Jan 22 14:46:50 2018 UTC
2 build 3.zip\build 3\MHLTH_YS_137_Source\JavaScript\resources\javaJDF-1.8.0\src\com\sun\crypto\provider DESedeWrapCipher.java Wed Sep 12 16:22:24 2018 UTC

88.2 Comparison summary

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

88.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

88.4 Active regular expressions

No regular expressions were active.

88.5 Comparison detail

  1   /*
  2    * Copyrig ht (c) 200 4, 2017, 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 co m.sun.cryp to.provide r;
  27  
  28   import jav a.security .*;
  29   import jav a.security .spec.*;
  30   import jav ax.crypto. *;
  31   import jav ax.crypto. spec.*;
  32  
  33   /**
  34    * This cl ass implem ents the C MS DESede  KeyWrap al gorithm as  defined
  35    * in <a h ref=http:/ /www.w3.or g/TR/xmlen c-core/#se c-Alg-Symm etricKeyWr ap>
  36    * "XML En cryption S yntax and  Processing " section  5.6.2
  37    * "CMS Tr iple DES K ey Wrap".
  38    * Note: o nly <code> CBC</code>  mode and  <code>NoPa dding</cod e> padding
  39    * scheme  can be use d for this  algorithm .
  40    *
  41    * @author  Valerie P eng
  42    *
  43    *
  44    * @see DE SedeCipher
  45    */
  46   public fin al class D ESedeWrapC ipher exte nds Cipher Spi {
  47  
  48       privat e static f inal byte[ ] IV2 = {
  49           (b yte) 0x4a,  (byte) 0x dd, (byte)  0xa2, (by te) 0x2c,
  50           (b yte) 0x79,  (byte) 0x e8, (byte)  0x21, (by te) 0x05
  51       };
  52  
  53       privat e static f inal int C HECKSUM_LE N = 8;
  54       privat e static f inal int I V_LEN = 8;
  55  
  56       /*
  57        * int ernal ciph er object  which does  the real  work.
  58        */
  59       privat e Feedback Cipher cip her;
  60  
  61       /*
  62        * iv  for (re-)i nitializin g the inte rnal ciphe r object.
  63        */
  64       privat e byte[] i v = null;
  65  
  66       /*
  67        * key  for re-in itializing  the inter nal cipher  object.
  68        */
  69       privat e Key ciph erKey = nu ll;
  70  
  71       /*
  72        * are  we encryp ting or de crypting?
  73        */
  74       privat e boolean  decrypting  = false;
  75  
  76       /**
  77        * Cre ates an in stance of  CMS DESede  KeyWrap c ipher with  default
  78        * mod e, i.e. "C BC" and pa dding sche me, i.e. " NoPadding" .
  79        */
  80       public  DESedeWra pCipher()  {
  81           ci pher = new  CipherBlo ckChaining (new DESed eCrypt());
  82       }
  83  
  84       /**
  85        * Set s the mode  of this c ipher. Onl y "CBC" mo de is acce pted for t his
  86        * cip her.
  87        *
  88        * @pa ram mode t he cipher  mode.
  89        *
  90        * @ex ception No SuchAlgori thmExcepti on if the  requested  cipher mod e
  91        * is  not "CBC".
  92        */
  93       protec ted void e ngineSetMo de(String  mode)
  94           th rows NoSuc hAlgorithm Exception  {
  95           if  (!mode.eq ualsIgnore Case("CBC" )) {
  96                throw ne w NoSuchAl gorithmExc eption(mod e + " cann ot be used ");
  97           }
  98       }
  99  
  100       /**
  101        * Set s the padd ing mechan ism of thi s cipher.  Only "NoPa dding" sch mem
  102        * is  accepted f or this ci pher.
  103        *
  104        * @pa ram paddin g the padd ing mechan ism.
  105        *
  106        * @ex ception No SuchPaddin gException  if the re quested pa dding mech anism
  107        * is  not "NoPad ding".
  108        */
  109       protec ted void e ngineSetPa dding(Stri ng padding )
  110           th rows NoSuc hPaddingEx ception {
  111           if  (!padding .equalsIgn oreCase("N oPadding") ) {
  112                throw ne w NoSuchPa ddingExcep tion(paddi ng + " can not be use d");
  113           }
  114       }
  115  
  116       /**
  117        * Ret urns the b lock size  (in bytes) , i.e. 8 b ytes.
  118        *
  119        * @re turn the b lock size  (in bytes) , i.e. 8 b ytes.
  120        */
  121       protec ted int en gineGetBlo ckSize() {
  122           re turn DESCo nstants.DE S_BLOCK_SI ZE;
  123       }
  124  
  125       /**
  126        * Ret urns the l ength in b ytes that  an output  buffer wou ld need to  be
  127        * giv en the inp ut length  <code>inpu tLen</code > (in byte s).
  128        *
  129        * <p> The actual  output le ngth of th e next <co de>update< /code> or
  130        * <co de>doFinal </code> ca ll may be  smaller th an the len gth return ed
  131        * by  this metho d.
  132        *
  133        * @pa ram inputL en the inp ut length  (in bytes) .
  134        *
  135        * @re turn the r equired ou tput buffe r size (in  bytes).
  136        */
  137       protec ted int en gineGetOut putSize(in t inputLen ) {
  138           //  can only  return an  upper-limi t if not i nitialized  yet.
  139           in t result =  0;
  140           if  (decrypti ng) {
  141                result =  inputLen  - 16; // C HECKSUM_LE N + IV_LEN ;
  142           }  else {
  143                result =  Math.addE xact(input Len, 16);
  144           }
  145           re turn (resu lt < 0? 0: result);
  146       }
  147  
  148       /**
  149        * Ret urns the i nitializat ion vector  (IV) in a  new buffe r.
  150        *
  151        * @re turn the i nitializat ion vector , or null  if the und erlying
  152        * alg orithm doe s not use  an IV, or  if the IV  has not ye t
  153        * bee n set.
  154        */
  155       protec ted byte[]  engineGet IV() {
  156           re turn (iv = = null) ?  null : iv. clone();
  157       }
  158  
  159       /**
  160        * Ini tializes t his cipher  with a ke y and a so urce of ra ndomness.
  161        *
  162        * <p> The cipher  only supp orts the f ollowing t wo operati on modes:< b>
  163        * Cip her.WRAP_M ODE, and < b>
  164        * Cip her.UNWRAP _MODE.
  165        * <p> For modes  other than  the above  two, Unsu pportedOpe rationExce ption
  166        * wil l be throw n.
  167        * <p> If this ci pher requi res an ini tializatio n vector ( IV), it wi ll get
  168        * it  from <code >random</c ode>.
  169        *
  170        * @pa ram opmode  the opera tion mode  of this ci pher. Only
  171        * <co de>WRAP_MO DE</code>  or <code>U NWRAP_MODE </code>) a re accepte d.
  172          * @param k ey the  PW        key.
  173        * @pa ram random  the sourc e of rando mness.
  174        *
  175        * @ex ception In validKeyEx ception if  the given  key is in appropriat e
  176        * or  if paramet ers are re quired but  not suppl ied.
  177        */
  178       protec ted void e ngineInit( int opmode , Key key,  SecureRan dom random )
  179           th rows Inval idKeyExcep tion {
  180           tr y {
  181                engineIn it(opmode,  key, (Alg orithmPara meterSpec)  null, ran dom);
  182           }  catch (Inv alidAlgori thmParamet erExceptio n iape) {
  183                // shoul d never ha ppen
  184                InvalidK eyExceptio n ike =
  185                    new  InvalidKey Exception( "Parameter s required ");
  186                ike.init Cause(iape );
  187                throw ik e;
  188           }
  189       }
  190  
  191       /**
  192        * Ini tializes t his cipher  with a ke y, a set o f algorith m paramete rs,
  193        * and  a source  of randomn ess.
  194        *
  195        * <p> The cipher  only supp orts the f ollowing t wo operati on modes:< b>
  196        * Cip her.WRAP_M ODE, and < b>
  197        * Cip her.UNWRAP _MODE.
  198        * <p> For modes  other than  the above  two, Unsu pportedOpe rationExce ption
  199        * wil l be throw n.
  200        * <p> If this ci pher requi res an ini tializatio n vector ( IV), it wi ll get
  201        * it  from <code >random</c ode>.
  202        *
  203        * @pa ram opmode  the opera tion mode  of this ci pher. Only
  204        * <co de>WRAP_MO DE</code>  or <code>U NWRAP_MODE </code>) a re accepte d.
  205          * @param k ey the  PW        key.
  206        * @pa ram params  the algor ithm param eters.
  207        * @pa ram random  the sourc e of rando mness.
  208        *
  209        * @ex ception In validKeyEx ception if  the given  key is in appropriat e.
  210        * @ex ception In validAlgor ithmParame terExcepti on if the  given algo rithm
  211        * par ameters ar e inapprop riate for  this ciphe r.
  212        */
  213       protec ted void e ngineInit( int opmode , Key key,
  214                                    AlgorithmP arameterSp ec params,
  215                                    SecureRand om random)
  216           th rows Inval idKeyExcep tion, Inva lidAlgorit hmParamete rException  {
  217           by te[] currI v = null;
  218           if  (opmode = = Cipher.W RAP_MODE)  {
  219                decrypti ng = false ;
  220                if (para ms == null ) {
  221                    iv =  new byte[ IV_LEN];
  222                    if ( random ==  null) {
  223                         random = S unJCE.getR andom();
  224                    }
  225                    rand om.nextByt es(iv);
  226                }
  227                else if  (params in stanceof I vParameter Spec) {
  228                    iv =  ((IvParam eterSpec)  params).ge tIV();
  229                } else {
  230                    thro w new Inva lidAlgorit hmParamete rException
  231                         ("Wrong pa rameter ty pe: IV exp ected");
  232                }
  233                currIv =  iv;
  234           }  else if (o pmode == C ipher.UNWR AP_MODE) {
  235                if (para ms != null ) {
  236                    thro w new Inva lidAlgorit hmParamete rException
  237                         ("No param eter accep ted for un wrapping k eys");
  238                }
  239                iv = nul l;
  240                decrypti ng = true;
  241                currIv =  IV2;
  242           }  else {
  243                throw ne w Unsuppor tedOperati onExceptio n("This ci pher can "  +
  244                    "onl y be used  for key wr apping and  unwrappin g");
  245           }
  246           ci pher.init( decrypting , key.getA lgorithm() , key.getE ncoded(),
  247                         currIv);
  248           ci pherKey =  key;
  249       }
  250  
  251       /**
  252        * Ini tializes t his cipher  with a ke y, a set o f algorith m paramete rs,
  253        * and  a source  of randomn ess.
  254        *
  255        * <p> The cipher  only supp orts the f ollowing t wo operati on modes:< b>
  256        * Cip her.WRAP_M ODE, and < b>
  257        * Cip her.UNWRAP _MODE.
  258        * <p> For modes  other than  the above  two, Unsu pportedOpe rationExce ption
  259        * wil l be throw n.
  260        * <p> If this ci pher requi res an ini tializatio n vector ( IV), it wi ll get
  261        * it  from <code >random</c ode>.
  262        *
  263        * @pa ram opmode  the opera tion mode  of this ci pher. Only
  264        * <co de>WRAP_MO DE</code>  or <code>U NWRAP_MODE </code>) a re accepte d.
  265          * @param k ey the  PW        key.
  266        * @pa ram params  the algor ithm param eters.
  267        * @pa ram random  the sourc e of rando mness.
  268        *
  269        * @ex ception In validKeyEx ception if  the given  key is in appropriat e.
  270        * @ex ception In validAlgor ithmParame terExcepti on if the  given algo rithm
  271        * par ameters ar e inapprop riate for  this ciphe r.
  272        */
  273       protec ted void e ngineInit( int opmode , Key key,
  274                                    AlgorithmP arameters  params,
  275                                    SecureRand om random)
  276           th rows Inval idKeyExcep tion, Inva lidAlgorit hmParamete rException  {
  277           Iv ParameterS pec ivSpec  = null;
  278           if  (params ! = null) {
  279                try {
  280                    DESe deParamete rs paramsE ng = new D ESedeParam eters();
  281                    para msEng.engi neInit(par ams.getEnc oded());
  282                    ivSp ec = param sEng.engin eGetParame terSpec(Iv ParameterS pec.class) ;
  283                } catch  (Exception  ex) {
  284                    Inva lidAlgorit hmParamete rException  iape =
  285                         new Invali dAlgorithm ParameterE xception
  286                             ("Wron g paramete r type: IV  expected" );
  287                    iape .initCause (ex);
  288                    thro w iape;
  289                }
  290           }
  291           en gineInit(o pmode, key , ivSpec,  random);
  292       }
  293  
  294       /**
  295        * Thi s operatio n is not s upported b y this cip her.
  296        * Sin ce it's im possible t o initiali ze this ci pher given  the
  297        * cur rent Ciphe r.engineIn it(...) im plementati on,
  298        * Ill egalStateE xception w ill always  be thrown  upon invo cation.
  299        *
  300        * @pa ram in the  input buf fer.
  301        * @pa ram inOffs et the off set in <co de>in</cod e> where t he input
  302        * sta rts.
  303        * @pa ram inLen  the input  length.
  304        *
  305        * @re turn n/a.
  306        *
  307        * @ex ception Il legalState Exception  upon invoc ation of t his method .
  308        */
  309       protec ted byte[]  engineUpd ate(byte[]  in, int i nOffset, i nt inLen)  {
  310           th row new Il legalState Exception( "Cipher ha s not been  initializ ed");
  311       }
  312  
  313       /**
  314        * Thi s operatio n is not s upported b y this cip her.
  315        * Sin ce it's im possible t o initiali ze this ci pher given  the
  316        * cur rent Ciphe r.engineIn it(...) im plementati on,
  317        * Ill egalStateE xception w ill always  be thrown  upon invo cation.
  318        *
  319        * @pa ram in the  input buf fer.
  320        * @pa ram inOffs et the off set in <co de>in</cod e> where t he input
  321        * sta rts.
  322        * @pa ram inLen  the input  length.
  323        * @pa ram out th e buffer f or the res ult.
  324        * @pa ram outOff set the of fset in <c ode>out</c ode> where  the resul t
  325        * is  stored.
  326        *
  327        * @re turn n/a.
  328        *
  329        * @ex ception Il legalState Exception  upon invoc ation of t his method .
  330        */
  331       protec ted int en gineUpdate (byte[] in , int inOf fset, int  inLen,
  332                                     byte[] ou t, int out Offset)
  333           th rows Short BufferExce ption {
  334           th row new Il legalState Exception( "Cipher ha s not been  initializ ed");
  335       }
  336  
  337       /**
  338        * Thi s operatio n is not s upported b y this cip her.
  339        * Sin ce it's im possible t o initiali ze this ci pher given  the
  340        * cur rent Ciphe r.engineIn it(...) im plementati on,
  341        * Ill egalStateE xception w ill always  be thrown  upon invo cation.
  342        *
  343        * @pa ram in the  input buf fer.
  344        * @pa ram inOffs et the off set in <co de>in</cod e> where t he input
  345        * sta rts.
  346        * @pa ram inLen  the input  length.
  347        *
  348        * @re turn the n ew buffer  with the r esult.
  349        *
  350        * @ex ception Il legalState Exception  upon invoc ation of t his method .
  351        */
  352       protec ted byte[]  engineDoF inal(byte[ ] in, int  inOffset,  int inLen)
  353           th rows Illeg alBlockSiz eException , BadPaddi ngExceptio n {
  354           th row new Il legalState Exception( "Cipher ha s not been  initializ ed");
  355       }
  356  
  357       /**
  358        * Thi s operatio n is not s upported b y this cip her.
  359        * Sin ce it's im possible t o initiali ze this ci pher given  the
  360        * cur rent Ciphe r.engineIn it(...) im plementati on,
  361        * Ill egalStateE xception w ill always  be thrown  upon invo cation.
  362        *
  363        * @pa ram in the  input buf fer.
  364        * @pa ram inOffs et the off set in <co de>in</cod e> where t he input
  365        * sta rts.
  366        * @pa ram inLen  the input  length.
  367        * @pa ram out th e buffer f or the res ult.
  368        * @pa ram outOff set the of set in <co de>out</co de> where  the result
  369        * is  stored.
  370        *
  371        * @re turn the n umber of b ytes store d in <code >out</code >.
  372        *
  373        * @ex ception Il legalState Exception  upon invoc ation of t his method .
  374        */
  375       protec ted int en gineDoFina l(byte[] i nput, int  inputOffse t, int inp utLen,
  376                                      byte[] o utput, int  outputOff set)
  377           th rows Illeg alBlockSiz eException , ShortBuf ferExcepti on,
  378                   BadPa ddingExcep tion {
  379           th row new Il legalState Exception( "Cipher ha s not been  initializ ed");
  380       }
  381  
  382       /**
  383        * Ret urns the p arameters  used with  this ciphe r.
  384        * Not e that nul l maybe re turned if  this ciphe r does not  use any
  385        * par ameters or  when it h as not be  set, e.g.  initialize d with
  386        * UNW RAP_MODE b ut wrapped  key data  has not be en given.
  387        *
  388        * @re turn the p arameters  used with  this ciphe r; can be  null.
  389        */
  390       protec ted Algori thmParamet ers engine GetParamet ers() {
  391           Al gorithmPar ameters pa rams = nul l;
  392           if  (iv != nu ll) {
  393                String a lgo = ciph erKey.getA lgorithm() ;
  394                try {
  395                    para ms = Algor ithmParame ters.getIn stance(alg o,
  396                         SunJCE.get Instance() );
  397                    para ms.init(ne w IvParame terSpec(iv ));
  398                } catch  (NoSuchAlg orithmExce ption nsae ) {
  399                    // s hould neve r happen
  400                    thro w new Runt imeExcepti on("Cannot  find " +  algo +
  401                         " Algorith mParameter s implemen tation in  SunJCE pro vider");
  402                } catch  (InvalidPa rameterSpe cException  ipse) {
  403                    // s hould neve r happen
  404                    thro w new Runt imeExcepti on("IvPara meterSpec  not suppor ted");
  405                }
  406           }
  407           re turn param s;
  408       }
  409  
  410       /**
  411        * Ret urns the k ey size of  the given  key objec t in numbe r of bits.
  412        * Thi s cipher a lways retu rn the sam e key size  as the DE Sede ciphe rs.
  413        *
  414        * @pa ram key th e key obje ct.
  415        *
  416        * @re turn the " effective"  key size  of the giv en key obj ect.
  417        *
  418        * @ex ception In validKeyEx ception if  <code>key </code> is  invalid.
  419        */
  420       protec ted int en gineGetKey Size(Key k ey) throws  InvalidKe yException  {
  421           by te[] encod ed = key.g etEncoded( );
  422           if  (encoded. length !=  24) {
  423                throw ne w InvalidK eyExceptio n("Invalid  key lengt h: " +
  424                    enco ded.length  + " bytes ");
  425           }
  426           //  Return th e effectiv e key leng th
  427           re turn 112;
  428       }
  429  
  430       /**
  431        * Wra p a key.
  432        *
  433        * @pa ram key th e key to b e wrapped.
  434        *
  435        * @re turn the w rapped key .
  436        *
  437        * @ex ception Il legalBlock SizeExcept ion if thi s cipher i s a block
  438        * cip her, no pa dding has  been reque sted, and  the length  of the
  439        * enc oding of t he key to  be wrapped  is not a
  440        * mul tiple of t he block s ize.
  441        *
  442        * @ex ception In validKeyEx ception if  it is imp ossible or  unsafe to
  443        * wra p the key  with this  cipher (e. g., a hard ware prote cted key i s
  444        * bei ng passed  to a softw are only c ipher).
  445        */
  446       protec ted byte[]  engineWra p(Key key)
  447           th rows Illeg alBlockSiz eException , InvalidK eyExceptio n {
  448           by te[] keyVa l = key.ge tEncoded() ;
  449           if  ((keyVal  == null) | | (keyVal. length ==  0)) {
  450                throw ne w InvalidK eyExceptio n("Cannot  get an enc oding of "  +
  451                                                 "the key  to be wra pped");
  452           }
  453  
  454           by te[] cks =  getChecks um(keyVal) ;
  455           by te[] in =  new byte[M ath.addExa ct(keyVal. length, CH ECKSUM_LEN )];
  456           Sy stem.array copy(keyVa l, 0, in,  0, keyVal. length);
  457           Sy stem.array copy(cks,  0, in, key Val.length , CHECKSUM _LEN);
  458  
  459           by te[] out =  new byte[ Math.addEx act(iv.len gth, in.le ngth)];
  460           Sy stem.array copy(iv, 0 , out, 0,  iv.length) ;
  461  
  462           ci pher.encry pt(in, 0,  in.length,  out, iv.l ength);
  463  
  464           //  reverse t he array c ontent
  465           fo r (int i =  0; i < ou t.length/2 ; i++) {
  466                byte tem p = out[i] ;
  467                out[i] =  out[out.l ength-1-i] ;
  468                out[out. length-1-i ] = temp;
  469           }
  470           tr y {
  471                cipher.i nit(false,  cipherKey .getAlgori thm(),
  472                             cipher Key.getEnc oded(), IV 2);
  473           }  catch (Inv alidKeyExc eption ike ) {
  474                // shoul d never ha ppen
  475                throw ne w RuntimeE xception(" Internal c ipher key  is corrupt ed");
  476           }
  477           by te[] out2  = new byte [out.lengt h];
  478           ci pher.encry pt(out, 0,  out.lengt h, out2, 0 );
  479  
  480           //  restore c ipher stat e to prior  to this c all
  481           tr y {
  482                cipher.i nit(decryp ting, ciph erKey.getA lgorithm() ,
  483                             cipher Key.getEnc oded(), iv );
  484           }  catch (Inv alidKeyExc eption ike ) {
  485                // shoul d never ha ppen
  486                throw ne w RuntimeE xception(" Internal c ipher key  is corrupt ed");
  487           }
  488           re turn out2;
  489       }
  490  
  491       /**
  492        * Unw rap a prev iously wra pped key.
  493        *
  494        * @pa ram wrappe dKey the k ey to be u nwrapped.
  495        *
  496        * @pa ram wrappe dKeyAlgori thm the al gorithm th e wrapped  key is for .
  497        *
  498        * @pa ram wrappe dKeyType t he type of  the wrapp ed key.
  499        * Thi s is one o f <code>Ci pher.SECRE T_KEY</cod e>,
  500        * <co de>Cipher. PRIVATE_KE Y</code>,  or <code>C ipher.PUBL IC_KEY</co de>.
  501        *
  502        * @re turn the u nwrapped k ey.
  503        *
  504        * @ex ception No SuchAlgori thmExcepti on if no i nstalled p roviders
  505        * can  create ke ys of type  <code>wra ppedKeyTyp e</code> f or the
  506        * <co de>wrapped KeyAlgorit hm</code>.
  507        *
  508        * @ex ception In validKeyEx ception if  <code>wra ppedKey</c ode> does  not
  509        * rep resent a w rapped key  of type < code>wrapp edKeyType< /code> for
  510        * the  <code>wra ppedKeyAlg orithm</co de>.
  511        */
  512       protec ted Key en gineUnwrap (byte[] wr appedKey,
  513                                     String wr appedKeyAl gorithm,
  514                                     int wrapp edKeyType)
  515           th rows Inval idKeyExcep tion, NoSu chAlgorith mException  {
  516           if  (wrappedK ey.length  == 0) {
  517                throw ne w InvalidK eyExceptio n("The wra pped key i s empty");
  518           }
  519           by te[] buffe r = new by te[wrapped Key.length ];
  520           ci pher.decry pt(wrapped Key, 0, wr appedKey.l ength, buf fer, 0);
  521  
  522           //  reverse a rray conte nt
  523           fo r (int i =  0; i < bu ffer.lengt h/2; i++)  {
  524                byte tem p = buffer [i];
  525                buffer[i ] = buffer [buffer.le ngth-1-i];
  526                buffer[b uffer.leng th-1-i] =  temp;
  527           }
  528           iv  = new byt e[IV_LEN];
  529           Sy stem.array copy(buffe r, 0, iv,  0, iv.leng th);
  530           ci pher.init( true, ciph erKey.getA lgorithm() , cipherKe y.getEncod ed(),
  531                         iv);
  532           by te[] buffe r2 = new b yte[buffer .length -  iv.length] ;
  533           ci pher.decry pt(buffer,  iv.length , buffer2. length,
  534                            buffer2 , 0);
  535           in t keyValLe n = buffer 2.length -  CHECKSUM_ LEN;
  536           by te[] cks =  getChecks um(buffer2 , 0, keyVa lLen);
  537           in t offset =  keyValLen ;
  538           fo r (int i =  0; i < CH ECKSUM_LEN ; i++) {
  539                if (buff er2[offset  + i] != c ks[i]) {
  540                    thro w new Inva lidKeyExce ption("Che cksum comp arison fai led");
  541                }
  542           }
  543           //  restore c ipher stat e to prior  to this c all
  544           ci pher.init( decrypting , cipherKe y.getAlgor ithm(),
  545                         cipherKey. getEncoded (), IV2);
  546           by te[] out =  new byte[ keyValLen] ;
  547           Sy stem.array copy(buffe r2, 0, out , 0, keyVa lLen);
  548           re turn Const ructKeys.c onstructKe y(out, wra ppedKeyAlg orithm,
  549                                                 wrappedK eyType);
  550       }
  551  
  552       privat e static f inal byte[ ] getCheck sum(byte[]  in) {
  553           re turn getCh ecksum(in,  0, in.len gth);
  554       }
  555       privat e static f inal byte[ ] getCheck sum(byte[]  in, int o ffset, int  len) {
  556           Me ssageDiges t md = nul l;
  557           tr y {
  558                md = Mes sageDigest .getInstan ce("SHA1") ;
  559           }  catch (NoS uchAlgorit hmExceptio n nsae) {
  560                throw ne w RuntimeE xception(" SHA1 messa ge digest  not availa ble");
  561           }
  562           md .update(in , offset,  len);
  563           by te[] cks =  new byte[ CHECKSUM_L EN];
  564           Sy stem.array copy(md.di gest(), 0,  cks, 0, c ks.length) ;
  565           re turn cks;
  566       }
  567   }