260. EPMO Open Source Coordination Office Redaction File Detail Report

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

260.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\pkcs11 P11RSACipher.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\pkcs11 P11RSACipher.java Wed Sep 12 17:53:16 2018 UTC

260.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 15 1316
Changed 14 30
Inserted 0 0
Removed 0 0

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

260.4 Active regular expressions

No regular expressions were active.

260.5 Comparison detail

  1   /*
  2    * Copyrig ht (c) 200 3, 2013, 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 .pkcs11;
  27  
  28   import jav a.security .*;
  29   import jav a.security .spec.Algo rithmParam eterSpec;
  30   import jav a.security .spec.*;
  31  
  32   import jav a.util.Loc ale;
  33  
  34   import jav ax.crypto. *;
  35   import jav ax.crypto. spec.*;
  36  
  37   import sta tic sun.se curity.pkc s11.Templa teManager. *;
  38   import sun .security. pkcs11.wra pper.*;
  39   import sta tic sun.se curity.pkc s11.wrappe r.PKCS11Co nstants.*;
  40   import sun .security. internal.s pec.TlsRsa PremasterS ecretParam eterSpec;
  41   import sun .security. util.KeyUt il;
  42  
  43   /**
  44    * RSA Cip her implem entation c lass. We c urrently o nly suppor t
  45    * PKCS#1  v1.5 paddi ng on top  of CKM_RSA _PKCS.
  46    *
  47    * @author   Andreas  Sterbenz
  48    * @since    1.5
  49    */
  50   final clas s P11RSACi pher exten ds CipherS pi {
  51  
  52       // min imum lengt h of PKCS# 1 v1.5 pad ding
  53       privat e final st atic int P KCS1_MIN_P ADDING_LEN GTH = 11;
  54  
  55       // con stant byte [] of leng th 0
  56       privat e final st atic byte[ ] B0 = new  byte[0];
  57  
  58       // mod e constant  for publi c key encr yption
  59       privat e final st atic int M ODE_ENCRYP T = 1;
  60       // mod e constant  for priva te key dec ryption
  61       privat e final st atic int M ODE_DECRYP T = 2;
  62       // mod e constant  for priva te key enc ryption (s igning)
  63       privat e final st atic int M ODE_SIGN     = 3;
  64       // mod e constant  for publi c key decr yption (ve rifying)
  65       privat e final st atic int M ODE_VERIFY   = 4;
  66  
  67       // pad ding type  constant f or NoPaddi ng
  68       privat e final st atic int P AD_NONE =  1;
  69       // pad ding type  constant f or PKCS1Pa dding
  70       privat e final st atic int P AD_PKCS1 =  2;
  71  
  72       // tok en instanc e
  73       privat e final To ken token;
  74  
  75       // alg orithm nam e (always  "RSA")
  76       privat e final St ring algor ithm;
  77  
  78       // mec hanism id
  79       privat e final lo ng mechani sm;
  80  
  81       // ass ociated se ssion, if  any
  82       privat e Session  session;
  83  
  84       // mod e, one of  MODE_* abo ve
  85       privat e int mode ;
  86  
  87       // pad ding, one  of PAD_* a bove
  88       privat e int padT ype;
  89  
  90       privat e byte[] b uffer;
  91       privat e int bufO fs;
  92  
  93       // key , if init( ) was call ed
  94       privat e P11Key p 11Key;
  95  
  96       // fla g indicati ng whether  an operat ion is ini tialized
  97       privat e boolean  initialize d;
  98  
  99       // max imum input  data size  allowed
  100       // for  decryptio n, this is  the lengt h of the k ey
  101       // for  encryptio n, length  of the key  minus min imum paddi ng length
  102       privat e int maxI nputSize;
  103  
  104       // max imum outpu t size. th is is the  length of  the key
  105       privat e int outp utSize;
  106  
  107         // cipher  parameter  for TLS RS A premaste PW     
  108       privat e Algorith mParameter Spec spec  = null;
  109  
  110       // the  source of  randomnes s
  111       privat e SecureRa ndom rando m;
  112  
  113       P11RSA Cipher(Tok en token,  String alg orithm, lo ng mechani sm)
  114                throws P KCS11Excep tion {
  115           su per();
  116           th is.token =  token;
  117           th is.algorit hm = "RSA" ;
  118           th is.mechani sm = mecha nism;
  119       }
  120  
  121       // mod es do not  make sense  for RSA,  but allow  ECB
  122       // see  JCE spec
  123       protec ted void e ngineSetMo de(String  mode) thro ws NoSuchA lgorithmEx ception {
  124           if  (mode.equ alsIgnoreC ase("ECB")  == false)  {
  125                throw ne w NoSuchAl gorithmExc eption("Un supported  mode " + m ode);
  126           }
  127       }
  128  
  129       protec ted void e ngineSetPa dding(Stri ng padding )
  130                throws N oSuchPaddi ngExceptio n {
  131           St ring lower Padding =  padding.to LowerCase( Locale.ENG LISH);
  132           if  (lowerPad ding.equal s("pkcs1pa dding")) {
  133                padType  = PAD_PKCS 1;
  134           }  else if (l owerPaddin g.equals(" nopadding" )) {
  135                padType  = PAD_NONE ;
  136           }  else {
  137                throw ne w NoSuchPa ddingExcep tion("Unsu pported pa dding " +  padding);
  138           }
  139       }
  140  
  141       // ret urn 0 as b lock size,  we are no t a block  cipher
  142       // see  JCE spec
  143       protec ted int en gineGetBlo ckSize() {
  144           re turn 0;
  145       }
  146  
  147       // ret urn the ou tput size
  148       // see  JCE spec
  149       protec ted int en gineGetOut putSize(in t inputLen ) {
  150           re turn outpu tSize;
  151       }
  152  
  153       // no  IV, return  null
  154       // see  JCE spec
  155       protec ted byte[]  engineGet IV() {
  156           re turn null;
  157       }
  158  
  159       // no  parameters , return n ull
  160       // see  JCE spec
  161       protec ted Algori thmParamet ers engine GetParamet ers() {
  162           re turn null;
  163       }
  164  
  165       // see  JCE spec
  166       protec ted void e ngineInit( int opmode , Key key,  SecureRan dom random )
  167                throws I nvalidKeyE xception {
  168           im plInit(opm ode, key);
  169       }
  170  
  171       // see  JCE spec
  172       protec ted void e ngineInit( int opmode , Key key,
  173                Algorith mParameter Spec param s, SecureR andom rand om)
  174                throws I nvalidKeyE xception,  InvalidAlg orithmPara meterExcep tion {
  175           if  (params ! = null) {
  176                if (!(pa rams insta nceof TlsR saPremaste rSecretPar ameterSpec )) {
  177                    thro w new Inva lidAlgorit hmParamete rException (
  178                             "Param eters not  supported" );
  179                }
  180                spec = p arams;
  181                  this.rando m = random    // for TLS  RSA prema ster  PW     
  182           }
  183           im plInit(opm ode, key);
  184       }
  185  
  186       // see  JCE spec
  187       protec ted void e ngineInit( int opmode , Key key,  Algorithm Parameters  params,
  188                SecureRa ndom rando m)
  189                throws I nvalidKeyE xception,  InvalidAlg orithmPara meterExcep tion {
  190           if  (params ! = null) {
  191                throw ne w InvalidA lgorithmPa rameterExc eption(
  192                             "Param eters not  supported" );
  193           }
  194           im plInit(opm ode, key);
  195       }
  196  
  197       privat e void imp lInit(int  opmode, Ke y key) thr ows Invali dKeyExcept ion {
  198           ca ncelOperat ion();
  199           p1 1Key = P11 KeyFactory .convertKe y(token, k ey, algori thm);
  200           bo olean encr ypt;
  201           if  (opmode = = Cipher.E NCRYPT_MOD E) {
  202                encrypt  = true;
  203           }  else if (o pmode == C ipher.DECR YPT_MODE)  {
  204                encrypt  = false;
  205           }  else if (o pmode == C ipher.WRAP _MODE) {
  206                if (p11K ey.isPubli c() == fal se) {
  207                    thro w new Inva lidKeyExce ption
  208                                      ("Wrap h as to be u sed with p ublic keys ");
  209                }
  210                // No fu rther setu p needed f or C_Wrap( ). We'll i nitialize  later if
  211                // we ca n't use C_ Wrap().
  212                return;
  213           }  else if (o pmode == C ipher.UNWR AP_MODE) {
  214                if (p11K ey.isPriva te() == fa lse) {
  215                    thro w new Inva lidKeyExce ption
  216                                      ("Unwrap  has to be  used with  private k eys");
  217                }
  218                // No fu rther setu p needed f or C_Unwra p(). We'll  initializ e later
  219                // if we  can't use  C_Unwrap( ).
  220                return;
  221           }  else {
  222                throw ne w InvalidK eyExceptio n("Unsuppo rted mode:  " + opmod e);
  223           }
  224           if  (p11Key.i sPublic())  {
  225                mode = e ncrypt ? M ODE_ENCRYP T : MODE_V ERIFY;
  226           }  else if (p 11Key.isPr ivate()) {
  227                mode = e ncrypt ? M ODE_SIGN :  MODE_DECR YPT;
  228           }  else {
  229                throw ne w InvalidK eyExceptio n("Unknown  key type:  " + p11Ke y);
  230           }
  231           in t n = (p11 Key.length () + 7) >>  3;
  232           ou tputSize =  n;
  233           bu ffer = new  byte[n];
  234           ma xInputSize  = ((padTy pe == PAD_ PKCS1 && e ncrypt) ?
  235                                 (n  - PKCS1_M IN_PADDING _LENGTH) :  n);
  236           tr y {
  237                initiali ze();
  238           }  catch (PKC S11Excepti on e) {
  239                throw ne w InvalidK eyExceptio n("init()  failed", e );
  240           }
  241       }
  242  
  243       privat e void can celOperati on() {
  244           to ken.ensure Valid();
  245           if  (initiali zed == fal se) {
  246                return;
  247           }
  248           in itialized  = false;
  249           if  ((session  == null)  || (token. explicitCa ncel == fa lse)) {
  250                return;
  251           }
  252           if  (session. hasObjects () == fals e) {
  253                session  = token.ki llSession( session);
  254                return;
  255           }
  256           tr y {
  257                PKCS11 p 11 = token .p11;
  258                int inLe n = maxInp utSize;
  259                int outL en = buffe r.length;
  260                switch ( mode) {
  261                case MOD E_ENCRYPT:
  262                    p11. C_Encrypt
  263                             (sessi on.id(), b uffer, 0,  inLen, buf fer, 0, ou tLen);
  264                    brea k;
  265                case MOD E_DECRYPT:
  266                    p11. C_Decrypt
  267                             (sessi on.id(), b uffer, 0,  inLen, buf fer, 0, ou tLen);
  268                    brea k;
  269                case MOD E_SIGN:
  270                    byte [] tmpBuff er = new b yte[maxInp utSize];
  271                    p11. C_Sign
  272                             (sessi on.id(), t mpBuffer);
  273                    brea k;
  274                case MOD E_VERIFY:
  275                    p11. C_VerifyRe cover
  276                             (sessi on.id(), b uffer, 0,  inLen, buf fer, 0, ou tLen);
  277                    brea k;
  278                default:
  279                    thro w new Prov iderExcept ion("inter nal error" );
  280                }
  281           }  catch (PKC S11Excepti on e) {
  282                // XXX e nsure this  always wo rks, ignor e error
  283           }
  284       }
  285  
  286       privat e void ens ureInitial ized() thr ows PKCS11 Exception  {
  287           to ken.ensure Valid();
  288           if  (initiali zed == fal se) {
  289                initiali ze();
  290           }
  291       }
  292  
  293       privat e void ini tialize()  throws PKC S11Excepti on {
  294           if  (session  == null) {
  295                session  = token.ge tOpSession ();
  296           }
  297           PK CS11 p11 =  token.p11 ;
  298           CK _MECHANISM  ckMechani sm = new C K_MECHANIS M(mechanis m);
  299           sw itch (mode ) {
  300           ca se MODE_EN CRYPT:
  301                p11.C_En cryptInit( session.id (), ckMech anism, p11 Key.keyID) ;
  302                break;
  303           ca se MODE_DE CRYPT:
  304                p11.C_De cryptInit( session.id (), ckMech anism, p11 Key.keyID) ;
  305                break;
  306           ca se MODE_SI GN:
  307                p11.C_Si gnInit(ses sion.id(),  ckMechani sm, p11Key .keyID);
  308                break;
  309           ca se MODE_VE RIFY:
  310                p11.C_Ve rifyRecove rInit(sess ion.id(),  ckMechanis m, p11Key. keyID);
  311                break;
  312           de fault:
  313                throw ne w Assertio nError("in ternal err or");
  314           }
  315           bu fOfs = 0;
  316           in itialized  = true;
  317       }
  318  
  319       privat e void imp lUpdate(by te[] in, i nt inOfs,  int inLen)  {
  320           tr y {
  321                ensureIn itialized( );
  322           }  catch (PKC S11Excepti on e) {
  323                throw ne w Provider Exception( "update()  failed", e );
  324           }
  325           if  ((inLen = = 0) || (i n == null) ) {
  326                return;
  327           }
  328           if  (bufOfs +  inLen > m axInputSiz e) {
  329                bufOfs =  maxInputS ize + 1;
  330                return;
  331           }
  332           Sy stem.array copy(in, i nOfs, buff er, bufOfs , inLen);
  333           bu fOfs += in Len;
  334       }
  335  
  336       privat e int impl DoFinal(by te[] out,  int outOfs , int outL en)
  337                throws B adPaddingE xception,  IllegalBlo ckSizeExce ption {
  338           if  (bufOfs >  maxInputS ize) {
  339                throw ne w IllegalB lockSizeEx ception("D ata must n ot be long er "
  340                    + "t han " + ma xInputSize  + " bytes ");
  341           }
  342           tr y {
  343                ensureIn itialized( );
  344                PKCS11 p 11 = token .p11;
  345                int n;
  346                switch ( mode) {
  347                case MOD E_ENCRYPT:
  348                    n =  p11.C_Encr ypt
  349                             (sessi on.id(), b uffer, 0,  bufOfs, ou t, outOfs,  outLen);
  350                    brea k;
  351                case MOD E_DECRYPT:
  352                    n =  p11.C_Decr ypt
  353                             (sessi on.id(), b uffer, 0,  bufOfs, ou t, outOfs,  outLen);
  354                    brea k;
  355                case MOD E_SIGN:
  356                    byte [] tmpBuff er = new b yte[bufOfs ];
  357                    Syst em.arrayco py(buffer,  0, tmpBuf fer, 0, bu fOfs);
  358                    tmpB uffer = p1 1.C_Sign(s ession.id( ), tmpBuff er);
  359                    if ( tmpBuffer. length > o utLen) {
  360                         throw new  BadPadding Exception( "Output bu ffer too s mall");
  361                    }
  362                    Syst em.arrayco py(tmpBuff er, 0, out , outOfs,  tmpBuffer. length);
  363                    n =  tmpBuffer. length;
  364                    brea k;
  365                case MOD E_VERIFY:
  366                    n =  p11.C_Veri fyRecover
  367                             (sessi on.id(), b uffer, 0,  bufOfs, ou t, outOfs,  outLen);
  368                    brea k;
  369                default:
  370                    thro w new Prov iderExcept ion("inter nal error" );
  371                }
  372                return n ;
  373           }  catch (PKC S11Excepti on e) {
  374                throw (B adPaddingE xception)n ew BadPadd ingExcepti on
  375                    ("do Final() fa iled").ini tCause(e);
  376           }  finally {
  377                initiali zed = fals e;
  378                session  = token.re leaseSessi on(session );
  379           }
  380       }
  381  
  382       // see  JCE spec
  383       protec ted byte[]  engineUpd ate(byte[]  in, int i nOfs, int  inLen) {
  384           im plUpdate(i n, inOfs,  inLen);
  385           re turn B0;
  386       }
  387  
  388       // see  JCE spec
  389       protec ted int en gineUpdate (byte[] in , int inOf s, int inL en,
  390                byte[] o ut, int ou tOfs) thro ws ShortBu fferExcept ion {
  391           im plUpdate(i n, inOfs,  inLen);
  392           re turn 0;
  393       }
  394  
  395       // see  JCE spec
  396       protec ted byte[]  engineDoF inal(byte[ ] in, int  inOfs, int  inLen)
  397                throws I llegalBloc kSizeExcep tion, BadP addingExce ption {
  398           im plUpdate(i n, inOfs,  inLen);
  399           in t n = impl DoFinal(bu ffer, 0, b uffer.leng th);
  400           by te[] out =  new byte[ n];
  401           Sy stem.array copy(buffe r, 0, out,  0, n);
  402           re turn out;
  403       }
  404  
  405       // see  JCE spec
  406       protec ted int en gineDoFina l(byte[] i n, int inO fs, int in Len,
  407                byte[] o ut, int ou tOfs) thro ws ShortBu fferExcept ion,
  408                IllegalB lockSizeEx ception, B adPaddingE xception {
  409           im plUpdate(i n, inOfs,  inLen);
  410           re turn implD oFinal(out , outOfs,  out.length  - outOfs) ;
  411       }
  412  
  413       privat e byte[] d oFinal() t hrows BadP addingExce ption,
  414                IllegalB lockSizeEx ception {
  415           by te[] t = n ew byte[20 48];
  416           in t n = impl DoFinal(t,  0, t.leng th);
  417           by te[] out =  new byte[ n];
  418           Sy stem.array copy(t, 0,  out, 0, n );
  419           re turn out;
  420       }
  421  
  422       // see  JCE spec
  423       protec ted byte[]  engineWra p(Key key)  throws In validKeyEx ception,
  424                IllegalB lockSizeEx ception {
  425           St ring keyAl g = key.ge tAlgorithm ();
  426           P1 1Key sKey  = null;
  427           tr y {
  428                // The c onversion  may fail,  e.g. tryin g to wrap  an AES key  on
  429                // a tok en that do es not sup port AES,  or when th e key size  is
  430                // not w ithin the  range supp orted by t he token.
  431                sKey = P 11SecretKe yFactory.c onvertKey( token, key , keyAlg);
  432           }  catch (Inv alidKeyExc eption ike ) {
  433                byte[] t oBeWrapped Key = key. getEncoded ();
  434                if (toBe WrappedKey  == null)  {
  435                    thro w new Inva lidKeyExce ption
  436                             ("wrap () failed,  no encodi ng availab le", ike);
  437                }
  438                // Direc tly encryp t the key  encoding w hen key co nversion f ailed
  439                implInit (Cipher.EN CRYPT_MODE , p11Key);
  440                implUpda te(toBeWra ppedKey, 0 , toBeWrap pedKey.len gth);
  441                try {
  442                    retu rn doFinal ();
  443                } catch  (BadPaddin gException  bpe) {
  444                    // s hould not  occur
  445                    thro w new Inva lidKeyExce ption("wra p() failed ", bpe);
  446                } finall y {
  447                    // R estore ori ginal mode
  448                    impl Init(Ciphe r.WRAP_MOD E, p11Key) ;
  449                }
  450           }
  451           Se ssion s =  null;
  452           tr y {
  453                s = toke n.getOpSes sion();
  454                return t oken.p11.C _WrapKey(s .id(), new  CK_MECHAN ISM(mechan ism),
  455                    p11K ey.keyID,  sKey.keyID );
  456           }  catch (PKC S11Excepti on e) {
  457                throw ne w InvalidK eyExceptio n("wrap()  failed", e );
  458           }  finally {
  459                token.re leaseSessi on(s);
  460           }
  461       }
  462  
  463       // see  JCE spec
  464       protec ted Key en gineUnwrap (byte[] wr appedKey,  String alg orithm,
  465                int type ) throws I nvalidKeyE xception,  NoSuchAlgo rithmExcep tion {
  466  
  467           bo olean isTl sRsaPremas terSecret  =
  468                    algo rithm.equa ls("TlsRsa PremasterS ecret");
  469           Ex ception fa ilover = n ull;
  470  
  471             // Should  C_Unwrap b e preferre d for non- TLS RSA pr emaster  PW      ?
  472           if  (token.su pportsRawS ecretKeyIm port()) {
  473                // XXX i mplement u nwrap usin g C_Unwrap () for all  keys
  474                implInit (Cipher.DE CRYPT_MODE , p11Key);
  475                try {
  476                    if ( wrappedKey .length >  maxInputSi ze) {
  477                         throw new  InvalidKey Exception( "Key is to o long for  unwrappin g");
  478                    }
  479  
  480                    byte [] encoded  = null;
  481                    impl Update(wra ppedKey, 0 , wrappedK ey.length) ;
  482                    try  {
  483                         encoded =  doFinal();
  484                    } ca tch (BadPa ddingExcep tion e) {
  485                         if (isTlsR saPremaste rSecret) {
  486                             failov er = e;
  487                         } else {
  488                             throw  new Invali dKeyExcept ion("Unwra pping fail ed", e);
  489                         }
  490                    } ca tch (Illeg alBlockSiz eException  e) {
  491                         // should  not occur,  handled w ith length  check abo ve
  492                         throw new  InvalidKey Exception( "Unwrappin g failed",  e);
  493                    }
  494  
  495                    if ( isTlsRsaPr emasterSec ret) {
  496                         if (!(spec  instanceo f TlsRsaPr emasterSec retParamet erSpec)) {
  497                             throw  new Illega lStateExce ption(
  498                                      "No TlsR saPremaste rSecretPar ameterSpec  specified ");
  499                         }
  500  
  501                          // polish  the TLS pr emaster  PW     
  502                         TlsRsaPrem asterSecre tParameter Spec psps  =
  503                                 (T lsRsaPrema sterSecret ParameterS pec)spec;
  504                         encoded =  KeyUtil.ch eckTlsPreM asterSecre tKey(
  505                                 ps ps.getClie ntVersion( ), psps.ge tServerVer sion(),
  506                                 ra ndom, enco ded, (fail over != nu ll));
  507                    }
  508  
  509                    retu rn Constru ctKeys.con structKey( encoded, a lgorithm,  type);
  510                } finall y {
  511                    // R estore ori ginal mode
  512                    impl Init(Ciphe r.UNWRAP_M ODE, p11Ke y);
  513                }
  514           }  else {
  515                Session  s = null;
  516                  SecretKey  PW      Key = null ;
  517                try {
  518                    try  {
  519                         s = token. getObjSess ion();
  520                         long keyTy pe = CKK_G ENERIC_SEC RET;
  521                         CK_ATTRIBU TE[] attri butes = ne w CK_ATTRI BUTE[] {
  522                                 ne w CK_ATTRI BUTE(CKA_C LASS, CKO_ SECRET_KEY ),
  523                                 ne w CK_ATTRI BUTE(CKA_K EY_TYPE, k eyType),
  524                             };
  525                         attributes  = token.g etAttribut es(
  526                                 O_ IMPORT, CK O_SECRET_K EY, keyTyp e, attribu tes);
  527                         long keyID  = token.p 11.C_Unwra pKey(s.id( ),
  528                                 ne w CK_MECHA NISM(mecha nism), p11 Key.keyID,
  529                                 wr appedKey,  attributes );
  530                          PW      Key = P11K ey. PW      Key(s, key ID,
  531                                 al gorithm, 4 8 << 3, at tributes);
  532                    } ca tch (PKCS1 1Exception  e) {
  533                         if (isTlsR saPremaste rSecret) {
  534                             failov er = e;
  535                         } else {
  536                             throw  new Invali dKeyExcept ion("unwra p() failed ", e);
  537                         }
  538                    }
  539  
  540                    if ( isTlsRsaPr emasterSec ret) {
  541                         TlsRsaPrem asterSecre tParameter Spec psps  =
  542                                 (T lsRsaPrema sterSecret ParameterS pec)spec;
  543  
  544                         // Please  use the tr icky failo ver as the  parameter  so that
  545                         // smart c ompiler wo n't dispos e the unus ed variabl e.
  546                          PW      Key = poli shPreMaste rSecretKey (token, s,
  547                                   failover,  PW      Key,
  548                                 ps ps.getClie ntVersion( ), psps.ge tServerVer sion());
  549                    }
  550  
  551                      return  PW      Key;
  552                } finall y {
  553                    toke n.releaseS ession(s);
  554                }
  555           }
  556       }
  557  
  558       // see  JCE spec
  559       protec ted int en gineGetKey Size(Key k ey) throws  InvalidKe yException  {
  560           in t n = P11K eyFactory. convertKey (token, ke y, algorit hm).length ();
  561           re turn n;
  562       }
  563  
  564       privat e static S ecretKey p olishPreMa sterSecret Key(
  565                Token to ken, Sessi on session ,
  566                Exceptio n failover , SecretKe y unwrappe dKey,
  567                int clie ntVersion,  int serve rVersion)  {
  568  
  569           Se cretKey ne wKey;
  570           CK _VERSION v ersion = n ew CK_VERS ION(
  571                    (cli entVersion  >>> 8) &  0xFF, clie ntVersion  & 0xFF);
  572           tr y {
  573                CK_ATTRI BUTE[] att ributes =  token.getA ttributes(
  574                         O_GENERATE , CKO_SECR ET_KEY,
  575                         CKK_GENERI C_SECRET,  new CK_ATT RIBUTE[0]) ;
  576                long key ID = token .p11.C_Gen erateKey(s ession.id( ),
  577                         new CK_MEC HANISM(CKM _SSL3_PRE_ MASTER_KEY _GEN, vers ion),
  578                         attributes );
  579                  newKey = P 11Key. PW      Key(sessio n,
  580                         keyID, "Tl sRsaPremas terSecret" , 48 << 3,  attribute s);
  581           }  catch (PKC S11Excepti on e) {
  582                throw ne w Provider Exception(
  583                          "Could not  generate  premaster  PW      ", e);
  584           }
  585  
  586           re turn (fail over == nu ll) ? unwr appedKey :  newKey;
  587       }
  588  
  589   }
  590  
  591   final clas s Construc tKeys {
  592       /**
  593        * Con struct a p ublic key  from its e ncoding.
  594        *
  595        * @pa ram encode dKey the e ncoding of  a public  key.
  596        *
  597        * @pa ram encode dKeyAlgori thm the al gorithm th e encodedK ey is for.
  598        *
  599        * @re turn a pub lic key co nstructed  from the e ncodedKey.
  600        */
  601       privat e static f inal Publi cKey const ructPublic Key(byte[]  encodedKe y,
  602                String e ncodedKeyA lgorithm)
  603                throws I nvalidKeyE xception,  NoSuchAlgo rithmExcep tion {
  604           tr y {
  605                KeyFacto ry keyFact ory =
  606                    KeyF actory.get Instance(e ncodedKeyA lgorithm);
  607                X509Enco dedKeySpec  keySpec =  new X509E ncodedKeyS pec(encode dKey);
  608                return k eyFactory. generatePu blic(keySp ec);
  609           }  catch (NoS uchAlgorit hmExceptio n nsae) {
  610                throw ne w NoSuchAl gorithmExc eption("No  installed  providers  " +
  611                                                      "ca n create k eys for th e " +
  612                                                      enc odedKeyAlg orithm +
  613                                                      "al gorithm",  nsae);
  614           }  catch (Inv alidKeySpe cException  ike) {
  615                throw ne w InvalidK eyExceptio n("Cannot  construct  public key ", ike);
  616           }
  617       }
  618  
  619       /**
  620        * Con struct a p rivate key  from its  encoding.
  621        *
  622        * @pa ram encode dKey the e ncoding of  a private  key.
  623        *
  624        * @pa ram encode dKeyAlgori thm the al gorithm th e wrapped  key is for .
  625        *
  626        * @re turn a pri vate key c onstructed  from the  encodedKey .
  627        */
  628       privat e static f inal Priva teKey cons tructPriva teKey(byte [] encoded Key,
  629                String e ncodedKeyA lgorithm)  throws Inv alidKeyExc eption,
  630                NoSuchAl gorithmExc eption {
  631           tr y {
  632                KeyFacto ry keyFact ory =
  633                    KeyF actory.get Instance(e ncodedKeyA lgorithm);
  634                PKCS8Enc odedKeySpe c keySpec  = new PKCS 8EncodedKe ySpec(enco dedKey);
  635                return k eyFactory. generatePr ivate(keyS pec);
  636           }  catch (NoS uchAlgorit hmExceptio n nsae) {
  637                throw ne w NoSuchAl gorithmExc eption("No  installed  providers  " +
  638                                                      "ca n create k eys for th e " +
  639                                                      enc odedKeyAlg orithm +
  640                                                      "al gorithm",  nsae);
  641           }  catch (Inv alidKeySpe cException  ike) {
  642                throw ne w InvalidK eyExceptio n("Cannot  construct  private ke y", ike);
  643           }
  644       }
  645  
  646       /**
  647          * Construc t a  PW        key from i ts encodin g.
  648        *
  649          * @param e ncodedKey  the encodi ng of a  PW        key.
  650        *
  651          * @param e ncodedKeyA lgorithm t he algorit hm the  PW        key is for .
  652        *
  653          * @return  PW        key constr ucted from  the encod edKey.
  654        */
  655       privat e static f inal Secre tKey const ructSecret Key(byte[]  encodedKe y,
  656                String e ncodedKeyA lgorithm)  {
  657           re turn new S ecretKeySp ec(encoded Key, encod edKeyAlgor ithm);
  658       }
  659  
  660       static  final Key  construct Key(byte[]  encoding,  String ke yAlgorithm ,
  661                int keyT ype) throw s InvalidK eyExceptio n, NoSuchA lgorithmEx ception {
  662           sw itch (keyT ype) {
  663           ca se Cipher. SECRET_KEY :
  664                return c onstructSe cretKey(en coding, ke yAlgorithm );
  665           ca se Cipher. PRIVATE_KE Y:
  666                return c onstructPr ivateKey(e ncoding, k eyAlgorith m);
  667           ca se Cipher. PUBLIC_KEY :
  668                return c onstructPu blicKey(en coding, ke yAlgorithm );
  669           de fault:
  670                throw ne w InvalidK eyExceptio n("Unknown  keytype "  + keyType );
  671           }
  672       }
  673   }