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

259.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 P11KeyStore.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 P11KeyStore.java Wed Sep 12 17:53:15 2018 UTC

259.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 23 5320
Changed 22 50
Inserted 0 0
Removed 0 0

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

259.4 Active regular expressions

No regular expressions were active.

259.5 Comparison detail

  1   /*
  2    * Copyrig ht (c) 200 3, 2016, 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.math.Big Integer;
  29  
  30   import jav a.io.Input Stream;
  31   import jav a.io.Outpu tStream;
  32   import jav a.io.IOExc eption;
  33   import jav a.io.ByteA rrayInputS tream;
  34   import jav a.io.Unsup portedEnco dingExcept ion;
  35  
  36   import jav a.util.Arr ays;
  37   import jav a.util.Col lections;
  38   import jav a.util.Dat e;
  39   import jav a.util.Enu meration;
  40   import jav a.util.Arr ayList;
  41   import jav a.util.Has hSet;
  42   import jav a.util.Has hMap;
  43   import jav a.util.Set ;
  44  
  45   import jav a.security .*;
  46   import jav a.security .KeyStore. *;
  47  
  48   import jav a.security .cert.Cert ificate;
  49   import jav a.security .cert.X509 Certificat e;
  50   import jav a.security .cert.Cert ificateFac tory;
  51   import jav a.security .cert.Cert ificateExc eption;
  52  
  53   import jav a.security .interface s.*;
  54   import jav a.security .spec.*;
  55  
  56   import jav ax.crypto. SecretKey;
  57   import jav ax.crypto. interfaces .*;
  58  
  59   import jav ax.securit y.auth.x50 0.X500Prin cipal;
  60   import jav ax.securit y.auth.log in.LoginEx ception;
  61   import jav ax.securit y.auth.cal lback.Call back;
  62   import jav ax.securit y.auth.cal lback.Pass wordCallba ck;
  63   import jav ax.securit y.auth.cal lback.Call backHandle r;
  64   import jav ax.securit y.auth.cal lback.Unsu pportedCal lbackExcep tion;
  65  
  66   import sun .security. util.Debug ;
  67   import sun .security. util.DerVa lue;
  68   import sun .security. util.ECUti l;
  69  
  70   import sun .security. ec.ECParam eters;
  71  
  72   import sun .security. pkcs11.Sec mod.*;
  73   import sta tic sun.se curity.pkc s11.P11Uti l.*;
  74  
  75   import sun .security. pkcs11.wra pper.*;
  76   import sta tic sun.se curity.pkc s11.wrappe r.PKCS11Co nstants.*;
  77  
  78   import sun .security. rsa.RSAKey Factory;
  79  
  80   final clas s P11KeySt ore extend s KeyStore Spi {
  81  
  82       privat e static f inal CK_AT TRIBUTE AT TR_CLASS_C ERT =
  83                             new CK _ATTRIBUTE (CKA_CLASS , CKO_CERT IFICATE);
  84       privat e static f inal CK_AT TRIBUTE AT TR_CLASS_P KEY =
  85                             new CK _ATTRIBUTE (CKA_CLASS , CKO_PRIV ATE_KEY);
  86       privat e static f inal CK_AT TRIBUTE AT TR_CLASS_S KEY =
  87                             new CK _ATTRIBUTE (CKA_CLASS , CKO_SECR ET_KEY);
  88  
  89       privat e static f inal CK_AT TRIBUTE AT TR_X509_CE RT_TYPE =
  90                             new CK _ATTRIBUTE (CKA_CERTI FICATE_TYP E, CKC_X_5 09);
  91  
  92       privat e static f inal CK_AT TRIBUTE AT TR_TOKEN_T RUE =
  93                             new CK _ATTRIBUTE (CKA_TOKEN , true);
  94  
  95       // XXX  for testi ng purpose s only
  96         //    - NSS does n't suppor t persiste nt  PW        keys
  97         //      (key type  gets mangl ed if  PW        key is a t oken key)
  98       //  -  if debug i s turned o n, then th is is set  to false
  99       privat e static C K_ATTRIBUT E ATTR_SKE Y_TOKEN_TR UE = ATTR_ TOKEN_TRUE ;
  100  
  101       privat e static f inal CK_AT TRIBUTE AT TR_TRUSTED _TRUE =
  102                             new CK _ATTRIBUTE (CKA_TRUST ED, true);
  103       privat e static f inal CK_AT TRIBUTE AT TR_PRIVATE _TRUE =
  104                             new CK _ATTRIBUTE (CKA_PRIVA TE, true);
  105  
  106       privat e static f inal long  NO_HANDLE  = -1;
  107       privat e static f inal long  FINDOBJECT S_MAX = 10 0;
  108       privat e static f inal Strin g ALIAS_SE P = "/";
  109  
  110       privat e static f inal boole an NSS_TES T = false;
  111       privat e static f inal Debug  debug =
  112                             Debug. getInstanc e("pkcs11k eystore");
  113       privat e static b oolean CKA _TRUSTED_S UPPORTED =  true;
  114  
  115       privat e final To ken token;
  116  
  117       // If  multiple c erts are f ound to sh are the sa me CKA_LAB EL
  118       // at  load time  (NSS-style  keystore) , then the  keystore  is read
  119       // and  the uniqu e keystore  aliases a re mapped  to the ent ries.
  120       // How ever, writ e capabili ties are d isabled.
  121       privat e boolean  writeDisab led = fals e;
  122  
  123       // Map  of unique  keystore  aliases to  entries i n the toke n
  124       privat e HashMap< String, Al iasInfo> a liasMap;
  125  
  126       // whe ther to us e NSS Secm od info fo r trust at tributes
  127       privat e final bo olean useS ecmodTrust ;
  128  
  129       // if  useSecmodT rust == tr ue, which  type of tr ust we are  intereste d in
  130       privat e Secmod.T rustType n ssTrustTyp e;
  131  
  132       /**
  133        * The  underlyin g token ma y contain  multiple c erts belon ging to th e
  134        * sam e "persona lity" (for  example,  a signing  cert and e ncryption  cert),
  135        * all  sharing t he same CK A_LABEL.   These must  be resolv ed
  136        * int o unique k eystore al iases.
  137        *
  138        * In  addition,  private ke ys and cer ts may not  have a CK A_LABEL.
  139        * It  is assumed  that a pr ivate key  and corres ponding ce rtificate
  140        * sha re the sam e CKA_ID,  and that t he CKA_ID  is unique  across the  token.
  141        * The  CKA_ID ma y not be h uman-reada ble.
  142        * The se pairs m ust be res olved into  unique ke ystore ali ases.
  143        *
  144          * Furtherm ore,  PW        keys are a ssumed to  have a CKA _LABEL
  145        * uni que across  the entir e token.
  146        *
  147        * Whe n the KeyS tore is lo aded, inst ances of t his class  are
  148          * created  to represe nt the pri vate keys/ PW        keys/certs
  149        * tha t reside o n the toke n.
  150        */
  151       privat e static c lass Alias Info {
  152  
  153           //  CKA_CLASS  - entry t ype
  154           pr ivate CK_A TTRIBUTE t ype = null ;
  155  
  156             // CKA_LAB EL of cert  and  PW        key
  157           pr ivate Stri ng label =  null;
  158  
  159           //  CKA_ID of  the priva te key/cer t pair
  160           pr ivate byte [] id = nu ll;
  161  
  162           //  CKA_TRUST ED - true  if cert is  trusted
  163           pr ivate bool ean truste d = false;
  164  
  165           //  either en d-entity c ert or tru sted cert  depending  on 'type'
  166           pr ivate X509 Certificat e cert = n ull;
  167  
  168           //  chain
  169           pr ivate X509 Certificat e chain[]  = null;
  170  
  171           //  true if C KA_ID for  private ke y and cert  match up
  172           pr ivate bool ean matche d = false;
  173  
  174           //  SecretKey Entry
  175           pu blic Alias Info(Strin g label) {
  176                this.typ e = ATTR_C LASS_SKEY;
  177                this.lab el = label ;
  178           }
  179  
  180           //  PrivateKe yEntry
  181           pu blic Alias Info(Strin g label,
  182                             byte[]  id,
  183                             boolea n trusted,
  184                             X509Ce rtificate  cert) {
  185                this.typ e = ATTR_C LASS_PKEY;
  186                this.lab el = label ;
  187                this.id  = id;
  188                this.tru sted = tru sted;
  189                this.cer t = cert;
  190           }
  191  
  192           pu blic Strin g toString () {
  193                StringBu ilder sb =  new Strin gBuilder() ;
  194                if (type  == ATTR_C LASS_PKEY)  {
  195                    sb.a ppend("\tt ype=[priva te key]\n" );
  196                } else i f (type ==  ATTR_CLAS S_SKEY) {
  197                      sb.append( "\ttype=[ PW        key]\n");
  198                } else i f (type ==  ATTR_CLAS S_CERT) {
  199                    sb.a ppend("\tt ype=[trust ed cert]\n ");
  200                }
  201                sb.appen d("\tlabel =[" + labe l + "]\n") ;
  202                if (id = = null) {
  203                    sb.a ppend("\ti d=[null]\n ");
  204                } else {
  205                    sb.a ppend("\ti d=" + P11K eyStore.ge tID(id) +  "\n");
  206                }
  207                sb.appen d("\ttrust ed=[" + tr usted + "] \n");
  208                sb.appen d("\tmatch ed=[" + ma tched + "] \n");
  209                if (cert  == null)  {
  210                    sb.a ppend("\tc ert=[null] \n");
  211                } else {
  212                    sb.a ppend("\tc ert=[\tsub ject: " +
  213                             cert.g etSubjectX 500Princip al() +
  214                             "\n\t\ tissuer: "  +
  215                             cert.g etIssuerX5 00Principa l() +
  216                             "\n\t\ tserialNum : " +
  217                             cert.g etSerialNu mber().toS tring() +
  218                             "]");
  219                }
  220                return s b.toString ();
  221           }
  222       }
  223  
  224       /**
  225        * cal lback hand ler for pa ssing pass word to Pr ovider.log in method
  226        */
  227       privat e static c lass Passw ordCallbac kHandler i mplements  CallbackHa ndler {
  228  
  229           pr ivate char [] passwor d;
  230  
  231           pr ivate Pass wordCallba ckHandler( char[] pas sword) {
  232                if (pass word != nu ll) {
  233                    this .password  = password .clone();
  234                }
  235           }
  236  
  237           pu blic void  handle(Cal lback[] ca llbacks)
  238                    thro ws IOExcep tion, Unsu pportedCal lbackExcep tion {
  239                if (!(ca llbacks[0]  instanceo f Password Callback))  {
  240                    thro w new Unsu pportedCal lbackExcep tion(callb acks[0]);
  241                }
  242                Password Callback p c = (Passw ordCallbac k)callback s[0];
  243                pc.setPa ssword(pas sword);  / / this clo nes the pa ssword if  not null
  244           }
  245  
  246           pr otected vo id finaliz e() throws  Throwable  {
  247                if (pass word != nu ll) {
  248                    Arra ys.fill(pa ssword, '  ');
  249                }
  250                super.fi nalize();
  251           }
  252       }
  253  
  254       /**
  255        * get TokenObjec t return v alue.
  256        *
  257        * if  object is  not found,  type is s et to null .
  258        * oth erwise, ty pe is set  to the req uested typ e.
  259        */
  260       privat e static c lass THand le {
  261           pr ivate fina l long han dle;               //  token obj ect handle
  262           pr ivate fina l CK_ATTRI BUTE type;         //  CKA_CLASS
  263  
  264           pr ivate THan dle(long h andle, CK_ ATTRIBUTE  type) {
  265                this.han dle = hand le;
  266                this.typ e = type;
  267           }
  268       }
  269  
  270       P11Key Store(Toke n token) {
  271           th is.token =  token;
  272           th is.useSecm odTrust =  token.prov ider.nssUs eSecmodTru st;
  273       }
  274  
  275       /**
  276        * Ret urns the k ey associa ted with t he given a lias.
  277        * The  key must  have been  associated  with
  278        * the  alias by  a call to  <code>setK eyEntry</c ode>,
  279        * or  by a call  to <code>s etEntry</c ode> with  a
  280        * <co de>Private KeyEntry</ code> or < code>Secre tKeyEntry< /code>.
  281        *
  282        * @pa ram alias  the alias  name
  283        * @pa ram passwo rd the pas sword, whi ch must be  <code>nul l</code>
  284        *
  285        * @re turn the r equested k ey, or nul l if the g iven alias  does not  exist
  286        * or  does not i dentify a  key-relate d entry.
  287        *
  288        * @ex ception No SuchAlgori thmExcepti on if the  algorithm  for recove ring the
  289        * key  cannot be  found
  290        * @ex ception Un recoverabl eKeyExcept ion if the  key canno t be recov ered
  291        */
  292       public  synchroni zed Key en gineGetKey (String al ias, char[ ] password )
  293                    thro ws NoSuchA lgorithmEx ception, U nrecoverab leKeyExcep tion {
  294  
  295           to ken.ensure Valid();
  296           if  (password  != null & & !token.c onfig.getK eyStoreCom patibility Mode()) {
  297                throw ne w NoSuchAl gorithmExc eption("pa ssword mus t be null" );
  298           }
  299  
  300           Al iasInfo al iasInfo =  aliasMap.g et(alias);
  301           if  (aliasInf o == null  || aliasIn fo.type ==  ATTR_CLAS S_CERT) {
  302                return n ull;
  303           }
  304  
  305           Se ssion sess ion = null ;
  306           tr y {
  307                session  = token.ge tOpSession ();
  308  
  309                if (alia sInfo.type  == ATTR_C LASS_PKEY)  {
  310                    THan dle h = ge tTokenObje ct(session ,
  311                                               aliasInfo. type,
  312                                               aliasInfo. id,
  313                                               null);
  314                    if ( h.type ==  ATTR_CLASS _PKEY) {
  315                         return loa dPkey(sess ion, h.han dle);
  316                    }
  317                } else {
  318                    THan dle h = ge tTokenObje ct(session ,
  319                                               ATTR_CLASS _SKEY,
  320                                               null,
  321                                               alias);
  322                    if ( h.type ==  ATTR_CLASS _SKEY) {
  323                         return loa dSkey(sess ion, h.han dle);
  324                    }
  325                }
  326  
  327                // did n ot find an ything
  328                return n ull;
  329           }  catch (PKC S11Excepti on | KeySt oreExcepti on e) {
  330                throw ne w Provider Exception( e);
  331           }  finally {
  332                token.re leaseSessi on(session );
  333           }
  334       }
  335  
  336       /**
  337        * Ret urns the c ertificate  chain ass ociated wi th the giv en alias.
  338        * The  certifica te chain m ust have b een associ ated with  the alias
  339        * by  a call to  <code>setK eyEntry</c ode>,
  340        * or  by a call  to <code>s etEntry</c ode> with  a
  341        * <co de>Private KeyEntry</ code>.
  342        *
  343        * @pa ram alias  the alias  name
  344        *
  345        * @re turn the c ertificate  chain (or dered with  the user' s certific ate first
  346        * and  the root  certificat e authorit y last), o r null if  the given  alias
  347        * doe s not exis t or does  not contai n a certif icate chai n
  348        */
  349       public  synchroni zed Certif icate[] en gineGetCer tificateCh ain(String  alias) {
  350  
  351           to ken.ensure Valid();
  352  
  353           Al iasInfo al iasInfo =  aliasMap.g et(alias);
  354           if  (aliasInf o == null  || aliasIn fo.type !=  ATTR_CLAS S_PKEY) {
  355                return n ull;
  356           }
  357           re turn alias Info.chain ;
  358       }
  359  
  360       /**
  361        * Ret urns the c ertificate  associate d with the  given ali as.
  362        *
  363        * <p>  If the gi ven alias  name ident ifies an e ntry
  364        * cre ated by a  call to <c ode>setCer tificateEn try</code> ,
  365        * or  created by  a call to  <code>set Entry</cod e> with a
  366        * <co de>Trusted Certificat eEntry</co de>,
  367        * the n the trus ted certif icate cont ained in t hat entry  is returne d.
  368        *
  369        * <p>  If the gi ven alias  name ident ifies an e ntry
  370        * cre ated by a  call to <c ode>setKey Entry</cod e>,
  371        * or  created by  a call to  <code>set Entry</cod e> with a
  372        * <co de>Private KeyEntry</ code>,
  373        * the n the firs t element  of the cer tificate c hain in th at entry
  374        * (if  a chain e xists) is  returned.
  375        *
  376        * @pa ram alias  the alias  name
  377        *
  378        * @re turn the c ertificate , or null  if the giv en alias d oes not ex ist or
  379        * doe s not cont ain a cert ificate.
  380        */
  381       public  synchroni zed Certif icate engi neGetCerti ficate(Str ing alias)  {
  382           to ken.ensure Valid();
  383  
  384           Al iasInfo al iasInfo =  aliasMap.g et(alias);
  385           if  (aliasInf o == null)  {
  386                return n ull;
  387           }
  388           re turn alias Info.cert;
  389       }
  390  
  391       /**
  392        * Ret urns the c reation da te of the  entry iden tified by  the given  alias.
  393        *
  394        * @pa ram alias  the alias  name
  395        *
  396        * @re turn the c reation da te of this  entry, or  null if t he given a lias does
  397        * not  exist
  398        */
  399       public  Date engi neGetCreat ionDate(St ring alias ) {
  400           to ken.ensure Valid();
  401           th row new Pr oviderExce ption(new  Unsupporte dOperation Exception( ));
  402       }
  403  
  404       /**
  405        * Ass igns the g iven key t o the give n alias, p rotecting  it with th e given
  406        * pas sword.
  407        *
  408        * <p> If the giv en key is  of type <c ode>java.s ecurity.Pr ivateKey</ code>,
  409        * it  must be ac companied  by a certi ficate cha in certify ing the
  410        * cor responding  public ke y.
  411        *
  412        * <p> If the giv en alias a lready exi sts, the k eystore in formation
  413        * ass ociated wi th it is o verridden  by the giv en key (an d possibly
  414        * cer tificate c hain).
  415        *
  416        * @pa ram alias  the alias  name
  417        * @pa ram key th e key to b e associat ed with th e alias
  418        * @pa ram passwo rd the pas sword to p rotect the  key
  419        * @pa ram chain  the certif icate chai n for the  correspond ing public
  420        * key  (only req uired if t he given k ey is of t ype
  421        * <co de>java.se curity.Pri vateKey</c ode>).
  422        *
  423        * @ex ception Ke yStoreExce ption if t he given k ey cannot  be protect ed, or
  424        * thi s operatio n fails fo r some oth er reason
  425        */
  426       public  synchroni zed void e ngineSetKe yEntry(Str ing alias,  Key key,
  427                                         char[ ] password ,
  428                                         Certi ficate[] c hain)
  429                    thro ws KeyStor eException  {
  430  
  431           to ken.ensure Valid();
  432           ch eckWrite() ;
  433  
  434           if  (!(key in stanceof P rivateKey)  && !(key  instanceof  SecretKey )) {
  435                throw ne w KeyStore Exception( "key must  be Private Key or Sec retKey");
  436           }  else if (k ey instanc eof Privat eKey && ch ain == nul l) {
  437                throw ne w KeyStore Exception
  438                    ("Pr ivateKey m ust be acc ompanied b y non-null  chain");
  439           }  else if (k ey instanc eof Secret Key && cha in != null ) {
  440                throw ne w KeyStore Exception
  441                    ("Se cretKey mu st be acco mpanied by  null chai n");
  442           }  else if (p assword !=  null &&
  443                         !token.con fig.getKey StoreCompa tibilityMo de()) {
  444                throw ne w KeyStore Exception( "Password  must be nu ll");
  445           }
  446  
  447           Ke yStore.Ent ry entry =  null;
  448           tr y {
  449                if (key  instanceof  PrivateKe y) {
  450                    entr y = new Ke yStore.Pri vateKeyEnt ry((Privat eKey)key,  chain);
  451                } else i f (key ins tanceof Se cretKey) {
  452                    entr y = new Ke yStore.Sec retKeyEntr y((SecretK ey)key);
  453                }
  454           }  catch (Nul lPointerEx ception |  IllegalArg umentExcep tion e) {
  455                throw ne w KeyStore Exception( e);
  456           }
  457           en gineSetEnt ry(alias,  entry, new  KeyStore. PasswordPr otection(p assword));
  458       }
  459  
  460       /**
  461        * Ass igns the g iven key ( that has a lready bee n protecte d) to the  given
  462        * ali as.
  463        *
  464        * <p> If the pro tected key  is of typ e
  465        * <co de>java.se curity.Pri vateKey</c ode>,
  466        * it  must be ac companied  by a certi ficate cha in certify ing the
  467        * cor responding  public ke y.
  468        *
  469        * <p> If the giv en alias a lready exi sts, the k eystore in formation
  470        * ass ociated wi th it is o verridden  by the giv en key (an d possibly
  471        * cer tificate c hain).
  472        *
  473        * @pa ram alias  the alias  name
  474        * @pa ram key th e key (in  protected  format) to  be associ ated with  the alias
  475        * @pa ram chain  the certif icate chai n for the  correspond ing public
  476        * key  (only use ful if the  protected  key is of  type
  477        * <co de>java.se curity.Pri vateKey</c ode>).
  478        *
  479        * @ex ception Ke yStoreExce ption if t his operat ion fails.
  480        */
  481       public  void engi neSetKeyEn try(String  alias, by te[] key,  Certificat e[] chain)
  482                    thro ws KeyStor eException  {
  483           to ken.ensure Valid();
  484           th row new Pr oviderExce ption(new  Unsupporte dOperation Exception( ));
  485       }
  486  
  487       /**
  488        * Ass igns the g iven certi ficate to  the given  alias.
  489        *
  490        * <p>  If the gi ven alias  identifies  an existi ng entry
  491        * cre ated by a  call to <c ode>setCer tificateEn try</code> ,
  492        * or  created by  a call to  <code>set Entry</cod e> with a
  493        * <co de>Trusted Certificat eEntry</co de>,
  494        * the  trusted c ertificate  in the ex isting ent ry
  495        * is  overridden  by the gi ven certif icate.
  496        *
  497        * @pa ram alias  the alias  name
  498        * @pa ram cert t he certifi cate
  499        *
  500        * @ex ception Ke yStoreExce ption if t he given a lias alrea dy exists  and does
  501        * not  identify  an entry c ontaining  a trusted  certificat e,
  502        * or  this opera tion fails  for some  other reas on.
  503        */
  504       public  synchroni zed void e ngineSetCe rtificateE ntry
  505           (S tring alia s, Certifi cate cert)  throws Ke yStoreExce ption {
  506  
  507           to ken.ensure Valid();
  508           ch eckWrite() ;
  509  
  510           if  (cert ==  null) {
  511                throw ne w KeyStore Exception( "invalid n ull certif icate");
  512           }
  513  
  514           Ke yStore.Ent ry entry =  null;
  515           en try = new  KeyStore.T rustedCert ificateEnt ry(cert);
  516           en gineSetEnt ry(alias,  entry, nul l);
  517       }
  518  
  519       /**
  520        * Del etes the e ntry ident ified by t he given a lias from  this keyst ore.
  521        *
  522        * @pa ram alias  the alias  name
  523        *
  524        * @ex ception Ke yStoreExce ption if t he entry c annot be r emoved.
  525        */
  526       public  synchroni zed void e ngineDelet eEntry(Str ing alias)
  527                    thro ws KeyStor eException  {
  528           to ken.ensure Valid();
  529  
  530           if  (token.is WriteProte cted()) {
  531                throw ne w KeyStore Exception( "token wri te-protect ed");
  532           }
  533           ch eckWrite() ;
  534           de leteEntry( alias);
  535       }
  536  
  537       /**
  538        * XXX  - not sur e whether  to keep th is
  539        */
  540       privat e boolean  deleteEntr y(String a lias) thro ws KeyStor eException  {
  541           Al iasInfo al iasInfo =  aliasMap.g et(alias);
  542           if  (aliasInf o != null)  {
  543  
  544                aliasMap .remove(al ias);
  545  
  546                try {
  547                    if ( aliasInfo. type == AT TR_CLASS_C ERT) {
  548                         // trusted  certifica te entry
  549                         return des troyCert(a liasInfo.i d);
  550                    } el se if (ali asInfo.typ e == ATTR_ CLASS_PKEY ) {
  551                         // private  key entry
  552                         return des troyPkey(a liasInfo.i d) &&
  553                                      destroyC hain(alias Info.id);
  554                    } el se if (ali asInfo.typ e == ATTR_ CLASS_SKEY ) {
  555                          //  PW        key entry
  556                         return des troySkey(a lias);
  557                    } el se {
  558                         throw new  KeyStoreEx ception("u nexpected  entry type ");
  559                    }
  560                } catch  (PKCS11Exc eption | C ertificate Exception  e) {
  561                    thro w new KeyS toreExcept ion(e);
  562                }
  563           }
  564           re turn false ;
  565       }
  566  
  567       /**
  568        * Lis ts all the  alias nam es of this  keystore.
  569        *
  570        * @re turn enume ration of  the alias  names
  571        */
  572       public  synchroni zed Enumer ation<Stri ng> engine Aliases()  {
  573           to ken.ensure Valid();
  574  
  575           //  don't wan t returned  enumerati on to iter ate off ac tual keySe t -
  576           //  otherwise  applicati ons that i terate and  modify th e keystore
  577           //  may run i nto concur rent modif ication pr oblems
  578           re turn Colle ctions.enu meration(n ew HashSet <String>(a liasMap.ke ySet()));
  579       }
  580  
  581       /**
  582        * Che cks if the  given ali as exists  in this ke ystore.
  583        *
  584        * @pa ram alias  the alias  name
  585        *
  586        * @re turn true  if the ali as exists,  false oth erwise
  587        */
  588       public  synchroni zed boolea n engineCo ntainsAlia s(String a lias) {
  589           to ken.ensure Valid();
  590           re turn alias Map.contai nsKey(alia s);
  591       }
  592  
  593       /**
  594        * Ret rieves the  number of  entries i n this key store.
  595        *
  596        * @re turn the n umber of e ntries in  this keyst ore
  597        */
  598       public  synchroni zed int en gineSize()  {
  599           to ken.ensure Valid();
  600           re turn alias Map.size() ;
  601       }
  602  
  603       /**
  604        * Ret urns true  if the ent ry identif ied by the  given ali as
  605        * was  created b y a call t o <code>se tKeyEntry< /code>,
  606        * or  created by  a call to  <code>set Entry</cod e> with a
  607        * <co de>Private KeyEntry</ code> or a  <code>Sec retKeyEntr y</code>.
  608        *
  609        * @pa ram alias  the alias  for the ke ystore ent ry to be c hecked
  610        *
  611        * @re turn true  if the ent ry identif ied by the  given ali as is a
  612        * key -related,  false othe rwise.
  613        */
  614       public  synchroni zed boolea n engineIs KeyEntry(S tring alia s) {
  615           to ken.ensure Valid();
  616  
  617           Al iasInfo al iasInfo =  aliasMap.g et(alias);
  618           if  (aliasInf o == null  || aliasIn fo.type ==  ATTR_CLAS S_CERT) {
  619                return f alse;
  620           }
  621           re turn true;
  622       }
  623  
  624       /**
  625        * Ret urns true  if the ent ry identif ied by the  given ali as
  626        * was  created b y a call t o <code>se tCertifica teEntry</c ode>,
  627        * or  created by  a call to  <code>set Entry</cod e> with a
  628        * <co de>Trusted Certificat eEntry</co de>.
  629        *
  630        * @pa ram alias  the alias  for the ke ystore ent ry to be c hecked
  631        *
  632        * @re turn true  if the ent ry identif ied by the  given ali as contain s a
  633        * tru sted certi ficate, fa lse otherw ise.
  634        */
  635       public  synchroni zed boolea n engineIs Certificat eEntry(Str ing alias)  {
  636           to ken.ensure Valid();
  637  
  638           Al iasInfo al iasInfo =  aliasMap.g et(alias);
  639           if  (aliasInf o == null  || aliasIn fo.type !=  ATTR_CLAS S_CERT) {
  640                return f alse;
  641           }
  642           re turn true;
  643       }
  644  
  645       /**
  646        * Ret urns the ( alias) nam e of the f irst keyst ore entry  whose cert ificate
  647        * mat ches the g iven certi ficate.
  648        *
  649        * <p> This metho d attempts  to match  the given  certificat e with eac h
  650        * key store entr y. If the  entry bein g consider ed was
  651        * cre ated by a  call to <c ode>setCer tificateEn try</code> ,
  652        * or  created by  a call to  <code>set Entry</cod e> with a
  653        * <co de>Trusted Certificat eEntry</co de>,
  654        * the n the give n certific ate is com pared to t hat entry' s certific ate.
  655        *
  656        * <p>  If the en try being  considered  was
  657        * cre ated by a  call to <c ode>setKey Entry</cod e>,
  658        * or  created by  a call to  <code>set Entry</cod e> with a
  659        * <co de>Private KeyEntry</ code>,
  660        * the n the give n certific ate is com pared to t he first
  661        * ele ment of th at entry's  certifica te chain.
  662        *
  663        * @pa ram cert t he certifi cate to ma tch with.
  664        *
  665        * @re turn the a lias name  of the fir st entry w ith matchi ng certifi cate,
  666        * or  null if no  such entr y exists i n this key store.
  667        */
  668       public  synchroni zed String  engineGet Certificat eAlias(Cer tificate c ert) {
  669           to ken.ensure Valid();
  670           En umeration< String> e  = engineAl iases();
  671           wh ile (e.has MoreElemen ts()) {
  672                String a lias = e.n extElement ();
  673                Certific ate tokenC ert = engi neGetCerti ficate(ali as);
  674                if (toke nCert != n ull && tok enCert.equ als(cert))  {
  675                    retu rn alias;
  676                }
  677           }
  678           re turn null;
  679       }
  680  
  681       /**
  682        * eng ineStore c urrently i s a No-op.
  683        * Ent ries are s tored to t he token d uring engi neSetEntry
  684        *
  685        * @pa ram stream  this must  be <code> null</code >
  686        * @pa ram passwo rd this mu st be <cod e>null</co de>
  687        */
  688       public  synchroni zed void e ngineStore (OutputStr eam stream , char[] p assword)
  689           th rows IOExc eption, No SuchAlgori thmExcepti on, Certif icateExcep tion {
  690           to ken.ensure Valid();
  691           if  (stream ! = null &&  !token.con fig.getKey StoreCompa tibilityMo de()) {
  692                throw ne w IOExcept ion("outpu t stream m ust be nul l");
  693           }
  694  
  695           if  (password  != null & & !token.c onfig.getK eyStoreCom patibility Mode()) {
  696                throw ne w IOExcept ion("passw ord must b e null");
  697           }
  698       }
  699  
  700       /**
  701        * eng ineStore c urrently i s a No-op.
  702        * Ent ries are s tored to t he token d uring engi neSetEntry
  703        *
  704        * @pa ram param  this must  be <code>n ull</code>
  705        *
  706        * @ex ception Il legalArgum entExcepti on if the  given
  707        *           <cod e>KeyStore .LoadStore Parameter< /code>
  708        *           inpu t is not < code>null< /code>
  709        */
  710       public  synchroni zed void e ngineStore (KeyStore. LoadStoreP arameter p aram)
  711           th rows IOExc eption, No SuchAlgori thmExcepti on, Certif icateExcep tion {
  712           to ken.ensure Valid();
  713           if  (param !=  null) {
  714                throw ne w IllegalA rgumentExc eption
  715                    ("Lo adStorePar ameter mus t be null" );
  716           }
  717       }
  718  
  719       /**
  720        * Loa ds the key store.
  721        *
  722        * @pa ram stream  the input  stream, w hich must  be <code>n ull</code>
  723        * @pa ram passwo rd the pas sword used  to unlock  the keyst ore,
  724        *           or < code>null< /code> if  the token  supports a
  725        *           CKF_ PROTECTED_ AUTHENTICA TION_PATH
  726        *
  727        * @ex ception IO Exception  if the giv en <code>s tream</cod e> is not
  728        *           <cod e>null</co de>, if th e token su pports a
  729        *           CKF_ PROTECTED_ AUTHENTICA TION_PATH  and a non- null
  730        *           pass word is gi ven, of if  the token  login ope ration fai led
  731        */
  732       public  synchroni zed void e ngineLoad( InputStrea m stream,  char[] pas sword)
  733           th rows IOExc eption, No SuchAlgori thmExcepti on, Certif icateExcep tion {
  734  
  735           to ken.ensure Valid();
  736  
  737           if  (NSS_TEST ) {
  738                ATTR_SKE Y_TOKEN_TR UE = new C K_ATTRIBUT E(CKA_TOKE N, false);
  739           }
  740  
  741           if  (stream ! = null &&  !token.con fig.getKey StoreCompa tibilityMo de()) {
  742                throw ne w IOExcept ion("input  stream mu st be null ");
  743           }
  744  
  745           if  (useSecmo dTrust) {
  746                nssTrust Type = Sec mod.TrustT ype.ALL;
  747           }
  748  
  749           tr y {
  750                if (pass word == nu ll) {
  751                    logi n(null);
  752                } else {
  753                    logi n(new Pass wordCallba ckHandler( password)) ;
  754                }
  755           }  catch(Logi nException  e) {
  756                Throwabl e cause =  e.getCause ();
  757                if (caus e instance of PKCS11E xception)  {
  758                    PKCS 11Exceptio n pe = (PK CS11Except ion) cause ;
  759                    if ( pe.getErro rCode() ==  CKR_PIN_I NCORRECT)  {
  760                         // if pass word is wr ong, the c ause of th e IOExcept ion
  761                         // should  be an Unre coverableK eyExceptio n
  762                         throw new  IOExceptio n("load fa iled",
  763                                 ne w Unrecove rableKeyEx ception(). initCause( e));
  764                    }
  765                }
  766                throw ne w IOExcept ion("load  failed", e );
  767           }
  768  
  769           tr y {
  770                if (mapL abels() ==  true) {
  771                    // C KA_LABELs  are shared  by multip le certs
  772                    writ eDisabled  = true;
  773                }
  774                if (debu g != null)  {
  775                    dump TokenMap() ;
  776                }
  777           }  catch (Key StoreExcep tion | PKC S11Excepti on e) {
  778                throw ne w IOExcept ion("load  failed", e );
  779           }
  780       }
  781  
  782       /**
  783        * Loa ds the key store usin g the give n
  784        * <co de>KeyStor e.LoadStor eParameter </code>.
  785        *
  786        * <p>  The <code >LoadStore Parameter. getProtect ionParamet er()</code >
  787        * met hod is exp ected to r eturn a <c ode>KeySto re.Passwor dProtectio n</code>
  788        * obj ect.  The  password i s retrieve d from tha t object a nd used
  789        * to  unlock the  PKCS#11 t oken.
  790        *
  791        * <p>  If the to ken suppor ts a CKF_P ROTECTED_A UTHENTICAT ION_PATH
  792        * the n the prov ided passw ord must b e <code>nu ll</code>.
  793        *
  794        * @pa ram param  the <code> KeyStore.L oadStorePa rameter</c ode>
  795        *
  796        * @ex ception Il legalArgum entExcepti on if the  given
  797        *           <cod e>KeyStore .LoadStore Parameter< /code> is  <code>null </code>,
  798        *           or i f that par ameter ret urns a <co de>null</c ode>
  799        *           <cod e>Protecti onParamete r</code> o bject.
  800        *           inpu t is not r ecognized
  801        * @ex ception IO Exception  if the tok en support s a
  802        *           CKF_ PROTECTED_ AUTHENTICA TION_PATH  and the pr ovided pas sword
  803        *           is n on-null, o r if the t oken login  operation  fails
  804        */
  805       public  synchroni zed void e ngineLoad( KeyStore.L oadStorePa rameter pa ram)
  806                    thro ws IOExcep tion, NoSu chAlgorith mException ,
  807                    Cert ificateExc eption {
  808  
  809           to ken.ensure Valid();
  810  
  811           if  (NSS_TEST ) {
  812                ATTR_SKE Y_TOKEN_TR UE = new C K_ATTRIBUT E(CKA_TOKE N, false);
  813           }
  814  
  815           //  if caller  wants to  pass a NUL L password ,
  816           //  force it  to pass a  non-NULL P asswordPro tection th at returns
  817           //  a NULL pa ssword
  818  
  819           if  (param ==  null) {
  820                throw ne w IllegalA rgumentExc eption
  821                             ("inva lid null L oadStorePa rameter");
  822           }
  823           if  (useSecmo dTrust) {
  824                if (para m instance of Secmod. KeyStoreLo adParamete r) {
  825                    nssT rustType =  ((Secmod. KeyStoreLo adParamete r)param).g etTrustTyp e();
  826                } else {
  827                    nssT rustType =  Secmod.Tr ustType.AL L;
  828                }
  829           }
  830  
  831           Ca llbackHand ler handle r;
  832           Ke yStore.Pro tectionPar ameter pp  = param.ge tProtectio nParameter ();
  833           if  (pp insta nceof Pass wordProtec tion) {
  834                char[] p assword =  ((Password Protection )pp).getPa ssword();
  835                if (pass word == nu ll) {
  836                    hand ler = null ;
  837                } else {
  838                    hand ler = new  PasswordCa llbackHand ler(passwo rd);
  839                }
  840           }  else if (p p instance of Callbac kHandlerPr otection)  {
  841                handler  = ((Callba ckHandlerP rotection) pp).getCal lbackHandl er();
  842           }  else {
  843                throw ne w IllegalA rgumentExc eption
  844                             ("Prot ectionPara meter must  be either  " +
  845                             "Passw ordProtect ion or Cal lbackHandl erProtecti on");
  846           }
  847  
  848           tr y {
  849                login(ha ndler);
  850                if (mapL abels() ==  true) {
  851                    // C KA_LABELs  are shared  by multip le certs
  852                    writ eDisabled  = true;
  853                }
  854                if (debu g != null)  {
  855                    dump TokenMap() ;
  856                }
  857           }  catch (Log inExceptio n | KeySto reExceptio n | PKCS11 Exception  e) {
  858                throw ne w IOExcept ion("load  failed", e );
  859           }
  860       }
  861  
  862       privat e void log in(Callbac kHandler h andler) th rows Login Exception  {
  863           if  ((token.t okenInfo.f lags & CKF _PROTECTED _AUTHENTIC ATION_PATH ) == 0) {
  864                token.pr ovider.log in(null, h andler);
  865           }  else {
  866                // token  supports  protected  authentica tion path
  867                // (exte rnal pin-p ad, for ex ample)
  868                if (hand ler != nul l &&
  869                    !tok en.config. getKeyStor eCompatibi lityMode() ) {
  870                    thro w new Logi nException ("can not  specify pa ssword if  token " +
  871                                      "support s protecte d authenti cation pat h");
  872                }
  873  
  874                // must  rely on ap plication- set or def ault handl er
  875                // if on e is neces sary
  876                token.pr ovider.log in(null, n ull);
  877           }
  878       }
  879  
  880       /**
  881        * Get  a <code>K eyStore.En try</code>  for the s pecified a lias
  882        *
  883        * @pa ram alias  get the <c ode>KeySto re.Entry</ code> for  this alias
  884        * @pa ram protPa ram this m ust be <co de>null</c ode>
  885        *
  886        * @re turn the < code>KeySt ore.Entry< /code> for  the speci fied alias ,
  887        *           or < code>null< /code> if  there is n o such ent ry
  888        *
  889        * @ex ception Ke yStoreExce ption if t he operati on failed
  890        * @ex ception No SuchAlgori thmExcepti on if the  algorithm  for recove ring the
  891        *           entr y cannot b e found
  892        * @ex ception Un recoverabl eEntryExce ption if t he specifi ed
  893        *           <cod e>protPara m</code> w ere insuff icient or  invalid
  894        *
  895        * @si nce 1.5
  896        */
  897       public  synchroni zed KeySto re.Entry e ngineGetEn try(String  alias,
  898                             KeySto re.Protect ionParamet er protPar am)
  899                    thro ws KeyStor eException , NoSuchAl gorithmExc eption,
  900                    Unre coverableE ntryExcept ion {
  901  
  902           to ken.ensure Valid();
  903  
  904           if  (protPara m != null  &&
  905                protPara m instance of KeyStor e.Password Protection  &&
  906                ((KeySto re.Passwor dProtectio n)protPara m).getPass word() !=  null &&
  907                !token.c onfig.getK eyStoreCom patibility Mode()) {
  908                throw ne w KeyStore Exception( "Protectio nParameter  must be n ull");
  909           }
  910  
  911           Al iasInfo al iasInfo =  aliasMap.g et(alias);
  912           if  (aliasInf o == null)  {
  913                if (debu g != null)  {
  914                    debu g.println( "engineGet Entry did  not find a lias [" +
  915                             alias  +
  916                             "] in  map");
  917                }
  918                return n ull;
  919           }
  920  
  921           Se ssion sess ion = null ;
  922           tr y {
  923                session  = token.ge tOpSession ();
  924  
  925                if (alia sInfo.type  == ATTR_C LASS_CERT)  {
  926                    // t rusted cer tificate e ntry
  927                    if ( debug != n ull) {
  928                         debug.prin tln("engin eGetEntry  found trus ted cert e ntry");
  929                    }
  930                    retu rn new Key Store.Trus tedCertifi cateEntry( aliasInfo. cert);
  931                } else i f (aliasIn fo.type ==  ATTR_CLAS S_SKEY) {
  932                      //  PW        key entry
  933                    if ( debug != n ull) {
  934                          debug.prin tln("engin eGetEntry  found  PW        key entry" );
  935                    }
  936  
  937                    THan dle h = ge tTokenObje ct
  938                             (sessi on, ATTR_C LASS_SKEY,  null, ali asInfo.lab el);
  939                    if ( h.type !=  ATTR_CLASS _SKEY) {
  940                         throw new  KeyStoreEx ception
  941                               ("expected  but could  not find  PW        key");
  942                    } el se {
  943                         SecretKey  skey = loa dSkey(sess ion, h.han dle);
  944                         return new  KeyStore. SecretKeyE ntry(skey) ;
  945                    }
  946                } else {
  947                    // p rivate key  entry
  948                    if ( debug != n ull) {
  949                         debug.prin tln("engin eGetEntry  found priv ate key en try");
  950                    }
  951  
  952                    THan dle h = ge tTokenObje ct
  953                             (sessi on, ATTR_C LASS_PKEY,  aliasInfo .id, null) ;
  954                    if ( h.type !=  ATTR_CLASS _PKEY) {
  955                         throw new  KeyStoreEx ception
  956                             ("expe cted but c ould not f ind privat e key");
  957                    } el se {
  958                         PrivateKey  pkey = lo adPkey(ses sion, h.ha ndle);
  959                         Certificat e[] chain  = aliasInf o.chain;
  960                         if ((pkey  != null) & & (chain ! = null)) {
  961                             return  new KeySt ore.Privat eKeyEntry( pkey, chai n);
  962                         } else {
  963                             if (de bug != nul l) {
  964                                 de bug.printl n
  965                                      ("engine GetEntry g ot null ce rt chain o r private  key");
  966                             }
  967                         }
  968                    }
  969                }
  970                return n ull;
  971           }  catch (PKC S11Excepti on pe) {
  972                throw ne w KeyStore Exception( pe);
  973           }  finally {
  974                token.re leaseSessi on(session );
  975           }
  976       }
  977  
  978       /**
  979        * Sav e a <code> KeyStore.E ntry</code > under th e specifie d alias.
  980        *
  981        * <p>  If an ent ry already  exists fo r the spec ified alia s,
  982        * it  is overrid den.
  983        *
  984        * <p>  This KeyS tore imple mentation  only suppo rts the st andard
  985        * ent ry types,  and only s upports X5 09Certific ates in
  986        * Tru stedCertif icateEntri es.  Also,  this impl ementation  does not  support
  987        * pro tecting en tries usin g a differ ent passwo rd
  988        * fro m the one  used for t oken login .
  989        *
  990        * <p>  Entries a re immedia tely store d on the t oken.
  991        *
  992        * @pa ram alias  save the < code>KeySt ore.Entry< /code> und er this al ias
  993        * @pa ram entry  the <code> Entry</cod e> to save
  994        * @pa ram protPa ram this m ust be <co de>null</c ode>
  995        *
  996        * @ex ception Ke yStoreExce ption if t his operat ion fails
  997        *
  998        * @si nce 1.5
  999        */
  1000       public  synchroni zed void e ngineSetEn try(String  alias, Ke yStore.Ent ry entry,
  1001                             KeySto re.Protect ionParamet er protPar am)
  1002                    thro ws KeyStor eException  {
  1003  
  1004           to ken.ensure Valid();
  1005           ch eckWrite() ;
  1006  
  1007           if  (protPara m != null  &&
  1008                protPara m instance of KeyStor e.Password Protection  &&
  1009                ((KeySto re.Passwor dProtectio n)protPara m).getPass word() !=  null &&
  1010                !token.c onfig.getK eyStoreCom patibility Mode()) {
  1011                throw ne w KeyStore Exception( new Unsupp ortedOpera tionExcept ion
  1012                                      ("Protec tionParame ter must b e null"));
  1013           }
  1014  
  1015           if  (token.is WriteProte cted()) {
  1016                throw ne w KeyStore Exception( "token wri te-protect ed");
  1017           }
  1018  
  1019           if  (entry in stanceof K eyStore.Tr ustedCerti ficateEntr y) {
  1020  
  1021                if (useS ecmodTrust  == false)  {
  1022                    // P KCS #11 do es not all ow app to  modify tru sted certs  -
  1023                    thro w new KeyS toreExcept ion(new Un supportedO perationEx ception
  1024                                          ("tr usted cert ificates m ay only be  set by "  +
  1025                                          "tok en initial ization ap plication" ));
  1026                }
  1027                Module m odule = to ken.provid er.nssModu le;
  1028                if ((mod ule.type ! = ModuleTy pe.KEYSTOR E) && (mod ule.type ! = ModuleTy pe.FIPS))  {
  1029                    // X XX allow T RUSTANCHOR  module
  1030                    thro w new KeyS toreExcept ion("Trust ed certifi cates can  only be "
  1031                         + "added t o the NSS  KeyStore m odule");
  1032                }
  1033                Certific ate cert =  ((Trusted Certificat eEntry)ent ry).getTru stedCertif icate();
  1034                if (cert  instanceo f X509Cert ificate ==  false) {
  1035                    thro w new KeyS toreExcept ion("Certi ficate mus t be an X5 09Certific ate");
  1036                }
  1037                X509Cert ificate xc ert = (X50 9Certifica te)cert;
  1038                AliasInf o info = a liasMap.ge t(alias);
  1039                if (info  != null)  {
  1040                    // X XX try to  update
  1041                    dele teEntry(al ias);
  1042                }
  1043                try {
  1044                    stor eCert(alia s, xcert);
  1045                    modu le.setTrus t(token, x cert);
  1046                    mapL abels();
  1047                } catch  (PKCS11Exc eption | C ertificate Exception  e) {
  1048                    thro w new KeyS toreExcept ion(e);
  1049                }
  1050  
  1051           }  else {
  1052  
  1053                if (entr y instance of KeyStor e.PrivateK eyEntry) {
  1054  
  1055                    Priv ateKey key  =
  1056                             ((KeyS tore.Priva teKeyEntry )entry).ge tPrivateKe y();
  1057                    if ( !(key inst anceof P11 Key) &&
  1058                         !(key inst anceof RSA PrivateKey ) &&
  1059                         !(key inst anceof DSA PrivateKey ) &&
  1060                         !(key inst anceof DHP rivateKey)  &&
  1061                         !(key inst anceof ECP rivateKey) ) {
  1062                         throw new  KeyStoreEx ception("u nsupported  key type:  " +
  1063                                                       ke y.getClass ().getName ());
  1064                    }
  1065  
  1066                    // o nly suppor t X509Cert ificate ch ains
  1067                    Cert ificate[]  chain =
  1068                         ((KeyStore .PrivateKe yEntry)ent ry).getCer tificateCh ain();
  1069                    if ( !(chain in stanceof X 509Certifi cate[])) {
  1070                         throw new  KeyStoreEx ception
  1071                             (new U nsupported OperationE xception
  1072                                      ("unsupp orted cert ificate ar ray type:  " +
  1073                                      chain.ge tClass().g etName())) ;
  1074                    }
  1075  
  1076                    try  {
  1077                         boolean up datedAlias  = false;
  1078                         Set<String > aliases  = aliasMap .keySet();
  1079                         for (Strin g oldAlias  : aliases ) {
  1080  
  1081                             // see  if there' s an exist ing entry  with the s ame info
  1082  
  1083                             AliasI nfo aliasI nfo = alia sMap.get(o ldAlias);
  1084                             if (al iasInfo.ty pe == ATTR _CLASS_PKE Y &&
  1085                                 al iasInfo.ce rt.getPubl icKey().eq uals
  1086                                               (chain[0]. getPublicK ey())) {
  1087  
  1088                                 //  found exi sting entr y -
  1089                                 //  caller is  renaming  entry or u pdating ce rt chain
  1090                                 //
  1091                                 //  set new C KA_LABEL/C KA_ID
  1092                                 //  and updat e certs if  necessary
  1093  
  1094                                 up datePkey(a lias,
  1095                                               aliasInfo. id,
  1096                                               (X509Certi ficate[])c hain,
  1097                                               !aliasInfo .cert.equa ls(chain[0 ]));
  1098                                 up datedAlias  = true;
  1099                                 br eak;
  1100                             }
  1101                         }
  1102  
  1103                         if (!updat edAlias) {
  1104                             // cal ler adding  new entry
  1105                             engine DeleteEntr y(alias);
  1106                             storeP key(alias,  (KeyStore .PrivateKe yEntry)ent ry);
  1107                         }
  1108  
  1109                    } ca tch (PKCS1 1Exception  | Certifi cateExcept ion pe) {
  1110                         throw new  KeyStoreEx ception(pe );
  1111                    }
  1112  
  1113                } else i f (entry i nstanceof  KeyStore.S ecretKeyEn try) {
  1114  
  1115                    KeyS tore.Secre tKeyEntry  ske = (Key Store.Secr etKeyEntry )entry;
  1116                    Secr etKey skey  = ske.get SecretKey( );
  1117  
  1118                    try  {
  1119                         // first c heck if th e key alre ady exists
  1120                         AliasInfo  aliasInfo  = aliasMap .get(alias );
  1121  
  1122                         if (aliasI nfo != nul l) {
  1123                             engine DeleteEntr y(alias);
  1124                         }
  1125                         storeSkey( alias, ske );
  1126  
  1127                    } ca tch (PKCS1 1Exception  pe) {
  1128                         throw new  KeyStoreEx ception(pe );
  1129                    }
  1130  
  1131                } else {
  1132                    thro w new KeyS toreExcept ion(new Un supportedO perationEx ception
  1133                         ("unsuppor ted entry  type: " +  entry.getC lass().get Name()));
  1134                }
  1135  
  1136                try {
  1137  
  1138                    // X XX  NSS do es not wri te out the  CKA_ID we  pass to t hem
  1139                    //
  1140                    // t herefore w e must re- map labels
  1141                    // ( can not si mply updat e aliasMap )
  1142  
  1143                    mapL abels();
  1144                    if ( debug != n ull) {
  1145                         dumpTokenM ap();
  1146                    }
  1147                } catch  (PKCS11Exc eption | C ertificate Exception  pe) {
  1148                    thro w new KeyS toreExcept ion(pe);
  1149                }
  1150           }
  1151  
  1152           if  (debug !=  null) {
  1153                debug.pr intln
  1154                    ("en gineSetEnt ry added n ew entry f or [" +
  1155                    alia s +
  1156                    "] t o token");
  1157           }
  1158       }
  1159  
  1160       /**
  1161        * Det ermines if  the keyst ore <code> Entry</cod e> for the  specified
  1162        * <co de>alias</ code> is a n instance  or subcla ss of the  specified
  1163        * <co de>entryCl ass</code> .
  1164        *
  1165        * @pa ram alias  the alias  name
  1166        * @pa ram entryC lass the e ntry class
  1167        *
  1168        * @re turn true  if the key store <cod e>Entry</c ode> for t he specifi ed
  1169        *           <cod e>alias</c ode> is an  instance  or subclas s of the
  1170        *           spec ified <cod e>entryCla ss</code>,  false oth erwise
  1171        */
  1172       public  synchroni zed boolea n engineEn tryInstanc eOf
  1173                    (Str ing alias,  Class<? e xtends Key Store.Entr y> entryCl ass) {
  1174           to ken.ensure Valid();
  1175           re turn super .engineEnt ryInstance Of(alias,  entryClass );
  1176       }
  1177  
  1178       privat e X509Cert ificate lo adCert(Ses sion sessi on, long o Handle)
  1179                    thro ws PKCS11E xception,  Certificat eException  {
  1180  
  1181           CK _ATTRIBUTE [] attrs =  new CK_AT TRIBUTE[]
  1182                             { new  CK_ATTRIBU TE(CKA_VAL UE) };
  1183           to ken.p11.C_ GetAttribu teValue(se ssion.id() , oHandle,  attrs);
  1184  
  1185           by te[] bytes  = attrs[0 ].getByteA rray();
  1186           if  (bytes ==  null) {
  1187                throw ne w Certific ateExcepti on
  1188                             ("unex pectedly r etrieved n ull byte a rray");
  1189           }
  1190           Ce rtificateF actory cf  = Certific ateFactory .getInstan ce("X.509" );
  1191           re turn (X509 Certificat e)cf.gener ateCertifi cate
  1192                             (new B yteArrayIn putStream( bytes));
  1193       }
  1194  
  1195       privat e X509Cert ificate[]  loadChain( Session se ssion,
  1196                                               X509Certif icate endC ert)
  1197                    thro ws PKCS11E xception,  Certificat eException  {
  1198  
  1199           Ar rayList<X5 09Certific ate> lChai n = null;
  1200  
  1201           if  (endCert. getSubject X500Princi pal().equa ls
  1202                (endCert .getIssuer X500Princi pal())) {
  1203                // self  signed
  1204                return n ew X509Cer tificate[]  { endCert  };
  1205           }  else {
  1206                lChain =  new Array List<X509C ertificate >();
  1207                lChain.a dd(endCert );
  1208           }
  1209  
  1210           //  try loadi ng remaini ng certs i n chain by  following
  1211           //  issuer->s ubject lin ks
  1212  
  1213           X5 09Certific ate next =  endCert;
  1214           wh ile (true)  {
  1215                CK_ATTRI BUTE[] att rs = new C K_ATTRIBUT E[] {
  1216                             ATTR_T OKEN_TRUE,
  1217                             ATTR_C LASS_CERT,
  1218                             new CK _ATTRIBUTE (CKA_SUBJE CT,
  1219                                      next.get IssuerX500 Principal( ).getEncod ed()) };
  1220                long[] c h = findOb jects(sess ion, attrs );
  1221  
  1222                if (ch = = null ||  ch.length  == 0) {
  1223                    // d one
  1224                    brea k;
  1225                } else {
  1226                    // i f more tha n one foun d, use fir st
  1227                    if ( debug != n ull && ch. length > 1 ) {
  1228                         debug.prin tln("engin eGetEntry  found " +
  1229                                      ch.lengt h +
  1230                                      " certif icate entr ies for su bject [" +
  1231                                      next.get IssuerX500 Principal( ).toString () +
  1232                                      "] in to ken - usin g first en try");
  1233                    }
  1234  
  1235                    next  = loadCer t(session,  ch[0]);
  1236                    lCha in.add(nex t);
  1237                    if ( next.getSu bjectX500P rincipal() .equals
  1238                         (next.getI ssuerX500P rincipal() )) {
  1239                         // self si gned
  1240                         break;
  1241                    }
  1242                }
  1243           }
  1244  
  1245           re turn lChai n.toArray( new X509Ce rtificate[ lChain.siz e()]);
  1246       }
  1247  
  1248       privat e SecretKe y loadSkey (Session s ession, lo ng oHandle )
  1249                    thro ws PKCS11E xception {
  1250  
  1251           CK _ATTRIBUTE [] attrs =  new CK_AT TRIBUTE[]  {
  1252                             new CK _ATTRIBUTE (CKA_KEY_T YPE) };
  1253           to ken.p11.C_ GetAttribu teValue(se ssion.id() , oHandle,  attrs);
  1254           lo ng kType =  attrs[0]. getLong();
  1255  
  1256           St ring keyTy pe = null;
  1257           in t keyLengt h = -1;
  1258  
  1259             // XXX NSS  mangles t he stored  key type f or  PW        key token  objects
  1260  
  1261           if  (kType ==  CKK_DES | | kType ==  CKK_DES3)  {
  1262                if (kTyp e == CKK_D ES) {
  1263                    keyT ype = "DES ";
  1264                    keyL ength = 64 ;
  1265                } else i f (kType = = CKK_DES3 ) {
  1266                    keyT ype = "DES ede";
  1267                    keyL ength = 19 2;
  1268                }
  1269           }  else {
  1270                if (kTyp e == CKK_A ES) {
  1271                    keyT ype = "AES ";
  1272                } else i f (kType = = CKK_BLOW FISH) {
  1273                    keyT ype = "Blo wfish";
  1274                } else i f (kType = = CKK_RC4)  {
  1275                    keyT ype = "ARC FOUR";
  1276                } else {
  1277                    if ( debug != n ull) {
  1278                         debug.prin tln("unkno wn key typ e [" +
  1279                                      kType +
  1280                                      "] - usi ng 'Generi c Secret'" );
  1281                    }
  1282                    keyT ype = "Gen eric Secre t";
  1283                }
  1284  
  1285                // XXX N SS problem  CKR_ATTRI BUTE_TYPE_ INVALID?
  1286                if (NSS_ TEST) {
  1287                    keyL ength = 12 8;
  1288                } else {
  1289                    attr s = new CK _ATTRIBUTE [] { new C K_ATTRIBUT E(CKA_VALU E_LEN) };
  1290                    toke n.p11.C_Ge tAttribute Value(sess ion.id(),  oHandle, a ttrs);
  1291                    keyL ength = (i nt)attrs[0 ].getLong( );
  1292                }
  1293           }
  1294  
  1295             return P11 Key. PW      Key(sessio n, oHandle , keyType,  keyLength , null);
  1296       }
  1297  
  1298       privat e PrivateK ey loadPke y(Session  session, l ong oHandl e)
  1299           th rows PKCS1 1Exception , KeyStore Exception  {
  1300  
  1301           CK _ATTRIBUTE [] attrs =  new CK_AT TRIBUTE[]  {
  1302                             new CK _ATTRIBUTE (CKA_KEY_T YPE) };
  1303           to ken.p11.C_ GetAttribu teValue(se ssion.id() , oHandle,  attrs);
  1304           lo ng kType =  attrs[0]. getLong();
  1305           St ring keyTy pe = null;
  1306           in t keyLengt h = 0;
  1307  
  1308           if  (kType ==  CKK_RSA)  {
  1309  
  1310                keyType  = "RSA";
  1311  
  1312                attrs =  new CK_ATT RIBUTE[] {  new CK_AT TRIBUTE(CK A_MODULUS)  };
  1313                token.p1 1.C_GetAtt ributeValu e(session. id(), oHan dle, attrs );
  1314                BigInteg er modulus  = attrs[0 ].getBigIn teger();
  1315                keyLengt h = modulu s.bitLengt h();
  1316  
  1317                // This  check will  combine o ur "don't  care" valu es here
  1318                // with  the system -wide min/ max values .
  1319                try {
  1320                    RSAK eyFactory. checkKeyLe ngths(keyL ength, nul l,
  1321                         -1, Intege r.MAX_VALU E);
  1322                } catch  (InvalidKe yException  e) {
  1323                    thro w new KeyS toreExcept ion(e.getM essage());
  1324                }
  1325  
  1326                return P 11Key.priv ateKey(ses sion,
  1327                                      oHandle,
  1328                                      keyType,
  1329                                      keyLengt h,
  1330                                      null);
  1331  
  1332           }  else if (k Type == CK K_DSA) {
  1333  
  1334                keyType  = "DSA";
  1335  
  1336                attrs =  new CK_ATT RIBUTE[] {  new CK_AT TRIBUTE(CK A_PRIME) } ;
  1337                token.p1 1.C_GetAtt ributeValu e(session. id(), oHan dle, attrs );
  1338                BigInteg er prime =  attrs[0]. getBigInte ger();
  1339                keyLengt h = prime. bitLength( );
  1340  
  1341                return P 11Key.priv ateKey(ses sion,
  1342                                      oHandle,
  1343                                      keyType,
  1344                                      keyLengt h,
  1345                                      null);
  1346  
  1347           }  else if (k Type == CK K_DH) {
  1348  
  1349                keyType  = "DH";
  1350  
  1351                attrs =  new CK_ATT RIBUTE[] {  new CK_AT TRIBUTE(CK A_PRIME) } ;
  1352                token.p1 1.C_GetAtt ributeValu e(session. id(), oHan dle, attrs );
  1353                BigInteg er prime =  attrs[0]. getBigInte ger();
  1354                keyLengt h = prime. bitLength( );
  1355  
  1356                return P 11Key.priv ateKey(ses sion,
  1357                                      oHandle,
  1358                                      keyType,
  1359                                      keyLengt h,
  1360                                      null);
  1361  
  1362           }  else if (k Type == CK K_EC) {
  1363  
  1364                attrs =  new CK_ATT RIBUTE[] {
  1365                    new  CK_ATTRIBU TE(CKA_EC_ PARAMS),
  1366                };
  1367                token.p1 1.C_GetAtt ributeValu e(session. id(), oHan dle, attrs );
  1368                byte[] e ncodedPara ms = attrs [0].getByt eArray();
  1369                try {
  1370                    ECPa rameterSpe c params =
  1371                         ECUtil.get ECParamete rSpec(null , encodedP arams);
  1372                    keyL ength = pa rams.getCu rve().getF ield().get FieldSize( );
  1373                } catch  (IOExcepti on e) {
  1374                    // w e do not w ant to acc ept key wi th unsuppo rted param eters
  1375                    thro w new KeyS toreExcept ion("Unsup ported par ameters",  e);
  1376                }
  1377  
  1378                return P 11Key.priv ateKey(ses sion, oHan dle, "EC",  keyLength , null);
  1379  
  1380           }  else {
  1381                if (debu g != null)  {
  1382                    debu g.println( "unknown k ey type ["  + kType +  "]");
  1383                }
  1384                throw ne w KeyStore Exception( "unknown k ey type");
  1385           }
  1386       }
  1387  
  1388  
  1389       /**
  1390        * XXX   On ibutt on, when y ou C_SetAt tribute(CK A_ID) for  a private  key
  1391        *       it not o nly change s the CKA_ ID of the  private ke y,
  1392        *       it chang es the CKA _ID of the  correspon ding cert  too.
  1393        *       And vice  versa.
  1394        *
  1395        * XXX   On ibutt on, CKR_DE VICE_ERROR  if you C_ SetAttribu te(CKA_ID)
  1396        *       for a pr ivate key,  and then  try to del ete the co rrespondin g cert.
  1397        *       So this  code rever ses the or der.
  1398        *       After th e cert is  first dest royed (if  necessary) ,
  1399        *       then the  CKA_ID of  the priva te key can  be change d successf ully.
  1400        *
  1401        * @pa ram replac eCert if t rue, then  caller is  updating a lias info  for
  1402        *                    existi ng cert (o nly update  CKA_ID/CK A_LABEL).
  1403        *                    if fal se, then c aller is u pdating ce rt chain
  1404        *                    (delet e old end  cert and a dd new cha in).
  1405        */
  1406       privat e void upd atePkey(St ring alias ,
  1407                             byte[]  cka_id,
  1408                             X509Ce rtificate[ ] chain,
  1409                             boolea n replaceC ert) throw s
  1410                    KeyS toreExcept ion, Certi ficateExce ption, PKC S11Excepti on {
  1411  
  1412           //  XXX
  1413           //
  1414           //  always se t replaceC ert to tru e
  1415           //
  1416           //  NSS does  not allow  resetting  of CKA_LAB EL on an e xisting ce rt
  1417           //  (C_SetAtt ribute cal l succeeds , but is i gnored)
  1418  
  1419           re placeCert  = true;
  1420  
  1421           Se ssion sess ion = null ;
  1422           tr y {
  1423                session  = token.ge tOpSession ();
  1424  
  1425                // first  get priva te key obj ect handle  and hang  onto it
  1426  
  1427                THandle  h = getTok enObject(s ession, AT TR_CLASS_P KEY, cka_i d, null);
  1428                long pKe yHandle;
  1429                if (h.ty pe == ATTR _CLASS_PKE Y) {
  1430                    pKey Handle = h .handle;
  1431                } else {
  1432                    thro w new KeyS toreExcept ion
  1433                             ("expe cted but c ould not f ind privat e key " +
  1434                             "with  CKA_ID " +
  1435                             getID( cka_id));
  1436                }
  1437  
  1438                // next  find exist ing end en tity cert
  1439  
  1440                h = getT okenObject (session,  ATTR_CLASS _CERT, cka _id, null) ;
  1441                if (h.ty pe != ATTR _CLASS_CER T) {
  1442                    thro w new KeyS toreExcept ion
  1443                             ("expe cted but c ould not f ind certif icate " +
  1444                             "with  CKA_ID " +
  1445                             getID( cka_id));
  1446                } else {
  1447                    if ( replaceCer t) {
  1448                         // replaci ng existin g cert and  chain
  1449                         destroyCha in(cka_id) ;
  1450                    } el se {
  1451                         // renamin g alias fo r existing  cert
  1452                         CK_ATTRIBU TE[] attrs  = new CK_ ATTRIBUTE[ ] {
  1453                             new CK _ATTRIBUTE (CKA_LABEL , alias),
  1454                             new CK _ATTRIBUTE (CKA_ID, a lias) };
  1455                         token.p11. C_SetAttri buteValue
  1456                             (sessi on.id(), h .handle, a ttrs);
  1457                    }
  1458                }
  1459  
  1460                // add n ew chain
  1461  
  1462                if (repl aceCert) {
  1463                    // a dd all cer ts in chai n
  1464                    stor eChain(ali as, chain) ;
  1465                } else {
  1466                    // a lready upd ated alias  info for  existing e nd cert -
  1467                    // j ust update  CA certs
  1468                    stor eCaCerts(c hain, 1);
  1469                }
  1470  
  1471                // final ly update  CKA_ID for  private k ey
  1472                //
  1473                // ibutt on may hav e already  done this  (that is o k)
  1474  
  1475                CK_ATTRI BUTE[] att rs = new C K_ATTRIBUT E[] {
  1476                                      new CK_A TTRIBUTE(C KA_ID, ali as) };
  1477                token.p1 1.C_SetAtt ributeValu e(session. id(), pKey Handle, at trs);
  1478  
  1479                if (debu g != null)  {
  1480                    debu g.println( "updatePke y set new  alias [" +
  1481                                      alias +
  1482                                      "] for p rivate key  entry");
  1483                }
  1484           }  finally {
  1485                token.re leaseSessi on(session );
  1486           }
  1487       }
  1488  
  1489       privat e void upd ateP11Pkey (String al ias, CK_AT TRIBUTE at tribute, P 11Key key)
  1490                    thro ws PKCS11E xception {
  1491  
  1492           //  if token  key, updat e alias.
  1493           //  if sessio n key, con vert to to ken key.
  1494  
  1495           Se ssion sess ion = null ;
  1496           tr y {
  1497                session  = token.ge tOpSession ();
  1498                if (key. tokenObjec t == true)  {
  1499  
  1500                    // t oken key -  set new C KA_ID
  1501  
  1502                    CK_A TTRIBUTE[]  attrs = n ew CK_ATTR IBUTE[] {
  1503                                      new CK_A TTRIBUTE(C KA_ID, ali as) };
  1504                    toke n.p11.C_Se tAttribute Value
  1505                                      (session .id(), key .keyID, at trs);
  1506                    if ( debug != n ull) {
  1507                         debug.prin tln("updat eP11Pkey s et new ali as [" +
  1508                                      alias +
  1509                                      "] for k ey entry") ;
  1510                    }
  1511                } else {
  1512  
  1513                    // s ession key  - convert  to token  key and se t CKA_ID
  1514  
  1515                    CK_A TTRIBUTE[]  attrs = n ew CK_ATTR IBUTE[] {
  1516                         ATTR_TOKEN _TRUE,
  1517                         new CK_ATT RIBUTE(CKA _ID, alias ),
  1518                    };
  1519                    if ( attribute  != null) {
  1520                         attrs = ad dAttribute (attrs, at tribute);
  1521                    }
  1522                    toke n.p11.C_Co pyObject(s ession.id( ), key.key ID, attrs) ;
  1523                    if ( debug != n ull) {
  1524                         debug.prin tln("updat eP11Pkey c opied priv ate sessio n key " +
  1525                                      "for ["  +
  1526                                      alias +
  1527                                      "] to to ken entry" );
  1528                    }
  1529                }
  1530           }  finally {
  1531                token.re leaseSessi on(session );
  1532           }
  1533       }
  1534  
  1535       privat e void sto reCert(Str ing alias,  X509Certi ficate cer t)
  1536                    thro ws PKCS11E xception,  Certificat eException  {
  1537  
  1538           Ar rayList<CK _ATTRIBUTE > attrList  = new Arr ayList<CK_ ATTRIBUTE> ();
  1539           at trList.add (ATTR_TOKE N_TRUE);
  1540           at trList.add (ATTR_CLAS S_CERT);
  1541           at trList.add (ATTR_X509 _CERT_TYPE );
  1542           at trList.add (new CK_AT TRIBUTE(CK A_SUBJECT,
  1543                                      cert.get SubjectX50 0Principal ().getEnco ded()));
  1544           at trList.add (new CK_AT TRIBUTE(CK A_ISSUER,
  1545                                      cert.get IssuerX500 Principal( ).getEncod ed()));
  1546           at trList.add (new CK_AT TRIBUTE(CK A_SERIAL_N UMBER,
  1547                                      cert.get SerialNumb er().toByt eArray())) ;
  1548           at trList.add (new CK_AT TRIBUTE(CK A_VALUE, c ert.getEnc oded()));
  1549  
  1550           if  (alias !=  null) {
  1551                attrList .add(new C K_ATTRIBUT E(CKA_LABE L, alias)) ;
  1552                attrList .add(new C K_ATTRIBUT E(CKA_ID,  alias));
  1553           }  else {
  1554                // ibutt on require s somethin g to be se t
  1555                // - ali as must be  unique
  1556                attrList .add(new C K_ATTRIBUT E(CKA_ID,
  1557                             getID( cert.getSu bjectX500P rincipal() .getName
  1558                                               (X500Princ ipal.CANON ICAL), cer t)));
  1559           }
  1560  
  1561           Se ssion sess ion = null ;
  1562           tr y {
  1563                session  = token.ge tOpSession ();
  1564                token.p1 1.C_Create Object(ses sion.id(),
  1565                             attrLi st.toArray (new CK_AT TRIBUTE[at trList.siz e()]));
  1566           }  finally {
  1567                token.re leaseSessi on(session );
  1568           }
  1569       }
  1570  
  1571       privat e void sto reChain(St ring alias , X509Cert ificate[]  chain)
  1572                    thro ws PKCS11E xception,  Certificat eException  {
  1573  
  1574           //  add new c hain
  1575           //
  1576           //  end cert  has CKA_LA BEL and CK A_ID set t o alias.
  1577           //  other cer ts in chai n have nei ther set.
  1578  
  1579           st oreCert(al ias, chain [0]);
  1580           st oreCaCerts (chain, 1) ;
  1581       }
  1582  
  1583       privat e void sto reCaCerts( X509Certif icate[] ch ain, int s tart)
  1584                    thro ws PKCS11E xception,  Certificat eException  {
  1585  
  1586           //  do not ad d duplicat e CA cert  if already  in token
  1587           //
  1588           //  XXX   ibu tton store s duplicat e CA certs , NSS does  not
  1589  
  1590           Se ssion sess ion = null ;
  1591           Ha shSet<X509 Certificat e> cacerts  = new Has hSet<X509C ertificate >();
  1592           tr y {
  1593                session  = token.ge tOpSession ();
  1594                CK_ATTRI BUTE[] att rs = new C K_ATTRIBUT E[] {
  1595                             ATTR_T OKEN_TRUE,
  1596                             ATTR_C LASS_CERT  };
  1597                long[] h andles = f indObjects (session,  attrs);
  1598  
  1599                // load  certs curr ently on t he token
  1600                for (lon g handle :  handles)  {
  1601                    cace rts.add(lo adCert(ses sion, hand le));
  1602                }
  1603           }  finally {
  1604                token.re leaseSessi on(session );
  1605           }
  1606  
  1607           fo r (int i =  start; i  < chain.le ngth; i++)  {
  1608                if (!cac erts.conta ins(chain[ i])) {
  1609                    stor eCert(null , chain[i] );
  1610                } else i f (debug ! = null) {
  1611                    debu g.println( "ignoring  duplicate  CA cert fo r [" +
  1612                             chain[ i].getSubj ectX500Pri ncipal() +
  1613                             "]");
  1614                }
  1615           }
  1616       }
  1617  
  1618       privat e void sto reSkey(Str ing alias,  KeyStore. SecretKeyE ntry ske)
  1619                    thro ws PKCS11E xception,  KeyStoreEx ception {
  1620  
  1621           Se cretKey sk ey = ske.g etSecretKe y();
  1622           //  No need t o specify  CKA_CLASS,  CKA_KEY_T YPE, CKA_V ALUE since
  1623           //  they are  handled in  P11Secret KeyFactory .createKey () method.
  1624           CK _ATTRIBUTE [] attrs =  new CK_AT TRIBUTE[]  {
  1625                ATTR_SKE Y_TOKEN_TR UE,
  1626                ATTR_PRI VATE_TRUE,
  1627                new CK_A TTRIBUTE(C KA_LABEL,  alias),
  1628           };
  1629           tr y {
  1630                P11Secre tKeyFactor y.convertK ey(token,  skey, null , attrs);
  1631           }  catch (Inv alidKeyExc eption ike ) {
  1632                // re-th row KeySto reExceptio n to match  javadoc
  1633                throw ne w KeyStore Exception( "Cannot co nvert to P KCS11 keys ", ike);
  1634           }
  1635  
  1636           //  update gl obal alias  map
  1637           al iasMap.put (alias, ne w AliasInf o(alias));
  1638  
  1639           if  (debug !=  null) {
  1640                  debug.prin tln("store Skey creat ed token  PW        key for ["  +
  1641                               alia s + "]");
  1642           }
  1643       }
  1644  
  1645       privat e static C K_ATTRIBUT E[] addAtt ribute(CK_ ATTRIBUTE[ ] attrs, C K_ATTRIBUT E attr) {
  1646           in t n = attr s.length;
  1647           CK _ATTRIBUTE [] newAttr s = new CK _ATTRIBUTE [n + 1];
  1648           Sy stem.array copy(attrs , 0, newAt trs, 0, n) ;
  1649           ne wAttrs[n]  = attr;
  1650           re turn newAt trs;
  1651       }
  1652  
  1653       privat e void sto rePkey(Str ing alias,  KeyStore. PrivateKey Entry pke)
  1654           th rows PKCS1 1Exception , Certific ateExcepti on, KeySto reExceptio n  {
  1655  
  1656           Pr ivateKey k ey = pke.g etPrivateK ey();
  1657           CK _ATTRIBUTE [] attrs =  null;
  1658  
  1659           //  If the ke y is a tok en object  on this to ken, updat e it inste ad
  1660           //  of creati ng a dupli cate key o bject.
  1661           //  Otherwise , treat a  P11Key lik e any othe r key, if  is is extr actable.
  1662           if  (key inst anceof P11 Key) {
  1663                P11Key p 11Key = (P 11Key)key;
  1664                if (p11K ey.tokenOb ject && (p 11Key.toke n == this. token)) {
  1665                    upda teP11Pkey( alias, nul l, p11Key) ;
  1666                    stor eChain(ali as, (X509C ertificate [])pke.get Certificat eChain());
  1667                    retu rn;
  1668                }
  1669           }
  1670  
  1671           bo olean useN DB = token .config.ge tNssNetsca peDbWorkar ound();
  1672           Pu blicKey pu blicKey =  pke.getCer tificate() .getPublic Key();
  1673  
  1674           if  (key inst anceof RSA PrivateKey ) {
  1675  
  1676                X509Cert ificate ce rt = (X509 Certificat e)pke.getC ertificate ();
  1677                attrs =  getRsaPriv KeyAttrs
  1678                    (ali as, (RSAPr ivateKey)k ey, cert.g etSubjectX 500Princip al());
  1679  
  1680           }  else if (k ey instanc eof DSAPri vateKey) {
  1681  
  1682                DSAPriva teKey dsaK ey = (DSAP rivateKey) key;
  1683  
  1684                CK_ATTRI BUTE[] idA ttrs = get IdAttribut es(key, pu blicKey, f alse, useN DB);
  1685                if (idAt trs[0] ==  null) {
  1686                    idAt trs[0] = n ew CK_ATTR IBUTE(CKA_ ID, alias) ;
  1687                }
  1688  
  1689                attrs =  new CK_ATT RIBUTE[] {
  1690                    ATTR _TOKEN_TRU E,
  1691                    ATTR _CLASS_PKE Y,
  1692                    ATTR _PRIVATE_T RUE,
  1693                    new  CK_ATTRIBU TE(CKA_KEY _TYPE, CKK _DSA),
  1694                    idAt trs[0],
  1695                    new  CK_ATTRIBU TE(CKA_PRI ME, dsaKey .getParams ().getP()) ,
  1696                    new  CK_ATTRIBU TE(CKA_SUB PRIME, dsa Key.getPar ams().getQ ()),
  1697                    new  CK_ATTRIBU TE(CKA_BAS E, dsaKey. getParams( ).getG()),
  1698                    new  CK_ATTRIBU TE(CKA_VAL UE, dsaKey .getX()),
  1699                };
  1700                if (idAt trs[1] !=  null) {
  1701                    attr s = addAtt ribute(att rs, idAttr s[1]);
  1702                }
  1703  
  1704                attrs =  token.getA ttributes
  1705                    (Tem plateManag er.O_IMPOR T, CKO_PRI VATE_KEY,  CKK_DSA, a ttrs);
  1706  
  1707                if (debu g != null)  {
  1708                    debu g.println( "storePkey  created D SA templat e");
  1709                }
  1710  
  1711           }  else if (k ey instanc eof DHPriv ateKey) {
  1712  
  1713                DHPrivat eKey dhKey  = (DHPriv ateKey)key ;
  1714  
  1715                CK_ATTRI BUTE[] idA ttrs = get IdAttribut es(key, pu blicKey, f alse, useN DB);
  1716                if (idAt trs[0] ==  null) {
  1717                    idAt trs[0] = n ew CK_ATTR IBUTE(CKA_ ID, alias) ;
  1718                }
  1719  
  1720                attrs =  new CK_ATT RIBUTE[] {
  1721                    ATTR _TOKEN_TRU E,
  1722                    ATTR _CLASS_PKE Y,
  1723                    ATTR _PRIVATE_T RUE,
  1724                    new  CK_ATTRIBU TE(CKA_KEY _TYPE, CKK _DH),
  1725                    idAt trs[0],
  1726                    new  CK_ATTRIBU TE(CKA_PRI ME, dhKey. getParams( ).getP()),
  1727                    new  CK_ATTRIBU TE(CKA_BAS E, dhKey.g etParams() .getG()),
  1728                    new  CK_ATTRIBU TE(CKA_VAL UE, dhKey. getX()),
  1729                };
  1730                if (idAt trs[1] !=  null) {
  1731                    attr s = addAtt ribute(att rs, idAttr s[1]);
  1732                }
  1733  
  1734                attrs =  token.getA ttributes
  1735                    (Tem plateManag er.O_IMPOR T, CKO_PRI VATE_KEY,  CKK_DH, at trs);
  1736  
  1737           }  else if (k ey instanc eof ECPriv ateKey) {
  1738  
  1739                ECPrivat eKey ecKey  = (ECPriv ateKey)key ;
  1740  
  1741                CK_ATTRI BUTE[] idA ttrs = get IdAttribut es(key, pu blicKey, f alse, useN DB);
  1742                if (idAt trs[0] ==  null) {
  1743                    idAt trs[0] = n ew CK_ATTR IBUTE(CKA_ ID, alias) ;
  1744                }
  1745  
  1746                byte[] e ncodedPara ms =
  1747                    ECUt il.encodeE CParameter Spec(null,  ecKey.get Params());
  1748                attrs =  new CK_ATT RIBUTE[] {
  1749                    ATTR _TOKEN_TRU E,
  1750                    ATTR _CLASS_PKE Y,
  1751                    ATTR _PRIVATE_T RUE,
  1752                    new  CK_ATTRIBU TE(CKA_KEY _TYPE, CKK _EC),
  1753                    idAt trs[0],
  1754                    new  CK_ATTRIBU TE(CKA_VAL UE, ecKey. getS()),
  1755                    new  CK_ATTRIBU TE(CKA_EC_ PARAMS, en codedParam s),
  1756                };
  1757                if (idAt trs[1] !=  null) {
  1758                    attr s = addAtt ribute(att rs, idAttr s[1]);
  1759                }
  1760  
  1761                attrs =  token.getA ttributes
  1762                    (Tem plateManag er.O_IMPOR T, CKO_PRI VATE_KEY,  CKK_EC, at trs);
  1763  
  1764                if (debu g != null)  {
  1765                    debu g.println( "storePkey  created E C template ");
  1766                }
  1767  
  1768           }  else if (k ey instanc eof P11Key ) {
  1769                // sensi tive/non-e xtractable  P11Key
  1770                P11Key p 11Key = (P 11Key)key;
  1771                if (p11K ey.token ! = this.tok en) {
  1772                    thro w new KeyS toreExcept ion
  1773                         ("Cannot m ove sensit ive keys a cross toke ns");
  1774                }
  1775                CK_ATTRI BUTE netsc apeDB = nu ll;
  1776                if (useN DB) {
  1777                    // N ote that t his curren tly fails  due to an  NSS bug.
  1778                    // T hey do not  allow the  CKA_NETSC APE_DB att ribute to  be
  1779                    // s pecified d uring C_Co pyObject()  and fail  with
  1780                    // C KR_ATTRIBU TE_READ_ON LY.
  1781                    // B ut if we d id not spe cify it, t hey would  fail with
  1782                    // C KA_TEMPLAT E_INCOMPLE TE, so lea ve this co de in here .
  1783                    CK_A TTRIBUTE[]  idAttrs =  getIdAttr ibutes(key , publicKe y, false,  true);
  1784                    nets capeDB = i dAttrs[1];
  1785                }
  1786                // Updat e the key  object.
  1787                updateP1 1Pkey(alia s, netscap eDB, p11Ke y);
  1788                storeCha in(alias,  (X509Certi ficate[])p ke.getCert ificateCha in());
  1789                return;
  1790  
  1791           }  else {
  1792                throw ne w KeyStore Exception( "unsupport ed key typ e: " + key );
  1793           }
  1794  
  1795           Se ssion sess ion = null ;
  1796           tr y {
  1797                session  = token.ge tOpSession ();
  1798  
  1799                // creat e private  key entry
  1800                token.p1 1.C_Create Object(ses sion.id(),  attrs);
  1801                if (debu g != null)  {
  1802                    debu g.println( "storePkey  created t oken key f or [" +
  1803                                      alias +
  1804                                      "]");
  1805                }
  1806           }  finally {
  1807                token.re leaseSessi on(session );
  1808           }
  1809  
  1810           st oreChain(a lias, (X50 9Certifica te[])pke.g etCertific ateChain() );
  1811       }
  1812  
  1813       privat e CK_ATTRI BUTE[] get RsaPrivKey Attrs(Stri ng alias,
  1814                                      RSAPriva teKey key,
  1815                                      X500Prin cipal subj ect) throw s PKCS11Ex ception {
  1816  
  1817           //  subject i s currentl y ignored  - could be  used to s et CKA_SUB JECT
  1818  
  1819           CK _ATTRIBUTE [] attrs =  null;
  1820           if  (key inst anceof RSA PrivateCrt Key) {
  1821  
  1822                if (debu g != null)  {
  1823                    debu g.println( "creating  RSAPrivate CrtKey att rs");
  1824                }
  1825  
  1826                RSAPriva teCrtKey r saKey = (R SAPrivateC rtKey)key;
  1827  
  1828                attrs =  new CK_ATT RIBUTE[] {
  1829                    ATTR _TOKEN_TRU E,
  1830                    ATTR _CLASS_PKE Y,
  1831                    ATTR _PRIVATE_T RUE,
  1832                    new  CK_ATTRIBU TE(CKA_KEY _TYPE, CKK _RSA),
  1833                    new  CK_ATTRIBU TE(CKA_ID,  alias),
  1834                    new  CK_ATTRIBU TE(CKA_MOD ULUS,
  1835                                      rsaKey.g etModulus( )),
  1836                    new  CK_ATTRIBU TE(CKA_PRI VATE_EXPON ENT,
  1837                                      rsaKey.g etPrivateE xponent()) ,
  1838                    new  CK_ATTRIBU TE(CKA_PUB LIC_EXPONE NT,
  1839                                      rsaKey.g etPublicEx ponent()),
  1840                    new  CK_ATTRIBU TE(CKA_PRI ME_1,
  1841                                      rsaKey.g etPrimeP() ),
  1842                    new  CK_ATTRIBU TE(CKA_PRI ME_2,
  1843                                      rsaKey.g etPrimeQ() ),
  1844                    new  CK_ATTRIBU TE(CKA_EXP ONENT_1,
  1845                                      rsaKey.g etPrimeExp onentP()),
  1846                    new  CK_ATTRIBU TE(CKA_EXP ONENT_2,
  1847                                      rsaKey.g etPrimeExp onentQ()),
  1848                    new  CK_ATTRIBU TE(CKA_COE FFICIENT,
  1849                                      rsaKey.g etCrtCoeff icient())  };
  1850                attrs =  token.getA ttributes
  1851                    (Tem plateManag er.O_IMPOR T, CKO_PRI VATE_KEY,  CKK_RSA, a ttrs);
  1852  
  1853           }  else {
  1854  
  1855                if (debu g != null)  {
  1856                    debu g.println( "creating  RSAPrivate Key attrs" );
  1857                }
  1858  
  1859                RSAPriva teKey rsaK ey = key;
  1860  
  1861                attrs =  new CK_ATT RIBUTE[] {
  1862                    ATTR _TOKEN_TRU E,
  1863                    ATTR _CLASS_PKE Y,
  1864                    ATTR _PRIVATE_T RUE,
  1865                    new  CK_ATTRIBU TE(CKA_KEY _TYPE, CKK _RSA),
  1866                    new  CK_ATTRIBU TE(CKA_ID,  alias),
  1867                    new  CK_ATTRIBU TE(CKA_MOD ULUS,
  1868                                      rsaKey.g etModulus( )),
  1869                    new  CK_ATTRIBU TE(CKA_PRI VATE_EXPON ENT,
  1870                                      rsaKey.g etPrivateE xponent())  };
  1871                attrs =  token.getA ttributes
  1872                    (Tem plateManag er.O_IMPOR T, CKO_PRI VATE_KEY,  CKK_RSA, a ttrs);
  1873           }
  1874  
  1875           re turn attrs ;
  1876       }
  1877  
  1878       /**
  1879        * Com pute the C KA_ID and/ or CKA_NET SCAPE_DB a ttributes  that shoul d be
  1880        * use d for this  private k ey. It use s the same  algorithm  to calcul ate the
  1881        * val ues as NSS . The publ ic and pri vate keys  MUST match  for the r esult to
  1882        * be  correct.
  1883        *
  1884        * It  returns a  2 element  array with  CKA_ID at  index 0 a nd CKA_NET SCAPE_DB
  1885        * at  index 1. T he boolean  flags det ermine wha t is to be  calculate d.
  1886        * If  false or i f we could  not calcu late the v alue, that  element i s null.
  1887        *
  1888        * NOT E that we  currently  do not use  the CKA_I D value ca lculated b y this
  1889        * met hod.
  1890        */
  1891       privat e CK_ATTRI BUTE[] get IdAttribut es(Private Key privat eKey,
  1892                PublicKe y publicKe y, boolean  id, boole an netscap eDb) {
  1893           CK _ATTRIBUTE [] attrs =  new CK_AT TRIBUTE[2] ;
  1894           if  ((id || n etscapeDb)  == false)  {
  1895                return a ttrs;
  1896           }
  1897           St ring alg =  privateKe y.getAlgor ithm();
  1898           if  (id && al g.equals(" RSA") && ( publicKey  instanceof  RSAPublic Key)) {
  1899                // CKA_N ETSCAPE_DB  not neede d for RSA  public key s
  1900                BigInteg er n = ((R SAPublicKe y)publicKe y).getModu lus();
  1901                attrs[0]  = new CK_ ATTRIBUTE( CKA_ID, sh a1(getMagn itude(n))) ;
  1902           }  else if (a lg.equals( "DSA") &&  (publicKey  instanceo f DSAPubli cKey)) {
  1903                BigInteg er y = ((D SAPublicKe y)publicKe y).getY();
  1904                if (id)  {
  1905                    attr s[0] = new  CK_ATTRIB UTE(CKA_ID , sha1(get Magnitude( y)));
  1906                }
  1907                if (nets capeDb) {
  1908                    attr s[1] = new  CK_ATTRIB UTE(CKA_NE TSCAPE_DB,  y);
  1909                }
  1910           }  else if (a lg.equals( "DH") && ( publicKey  instanceof  DHPublicK ey)) {
  1911                BigInteg er y = ((D HPublicKey )publicKey ).getY();
  1912                if (id)  {
  1913                    attr s[0] = new  CK_ATTRIB UTE(CKA_ID , sha1(get Magnitude( y)));
  1914                }
  1915                if (nets capeDb) {
  1916                    attr s[1] = new  CK_ATTRIB UTE(CKA_NE TSCAPE_DB,  y);
  1917                }
  1918           }  else if (a lg.equals( "EC") && ( publicKey  instanceof  ECPublicK ey)) {
  1919                ECPublic Key ecPub  = (ECPubli cKey)publi cKey;
  1920                ECPoint  point = ec Pub.getW() ;
  1921                ECParame terSpec pa rams = ecP ub.getPara ms();
  1922                byte[] e ncodedPoin t = ECUtil .encodePoi nt(point,  params.get Curve());
  1923                if (id)  {
  1924                    attr s[0] = new  CK_ATTRIB UTE(CKA_ID , sha1(enc odedPoint) );
  1925                }
  1926                if (nets capeDb) {
  1927                    attr s[1] = new  CK_ATTRIB UTE(CKA_NE TSCAPE_DB,  encodedPo int);
  1928                }
  1929           }  else {
  1930                throw ne w RuntimeE xception(" Unknown ke y algorith m " + alg) ;
  1931           }
  1932           re turn attrs ;
  1933       }
  1934  
  1935       /**
  1936        * ret urn true i f cert des troyed
  1937        */
  1938       privat e boolean  destroyCer t(byte[] c ka_id)
  1939                    thro ws PKCS11E xception,  KeyStoreEx ception {
  1940           Se ssion sess ion = null ;
  1941           tr y {
  1942                session  = token.ge tOpSession ();
  1943                THandle  h = getTok enObject(s ession, AT TR_CLASS_C ERT, cka_i d, null);
  1944                if (h.ty pe != ATTR _CLASS_CER T) {
  1945                    retu rn false;
  1946                }
  1947  
  1948                token.p1 1.C_Destro yObject(se ssion.id() , h.handle );
  1949                if (debu g != null)  {
  1950                    debu g.println( "destroyCe rt destroy ed cert wi th CKA_ID  [" +
  1951                                                       ge tID(cka_id ) +
  1952                                                       "] ");
  1953                }
  1954                return t rue;
  1955           }  finally {
  1956                token.re leaseSessi on(session );
  1957           }
  1958       }
  1959  
  1960       /**
  1961        * ret urn true i f chain de stroyed
  1962        */
  1963       privat e boolean  destroyCha in(byte[]  cka_id)
  1964           th rows PKCS1 1Exception , Certific ateExcepti on, KeySto reExceptio n {
  1965  
  1966           Se ssion sess ion = null ;
  1967           tr y {
  1968                session  = token.ge tOpSession ();
  1969  
  1970                THandle  h = getTok enObject(s ession, AT TR_CLASS_C ERT, cka_i d, null);
  1971                if (h.ty pe != ATTR _CLASS_CER T) {
  1972                    if ( debug != n ull) {
  1973                         debug.prin tln("destr oyChain co uld not fi nd " +
  1974                             "end e ntity cert  with CKA_ ID [0x" +
  1975                             Functi ons.toHexS tring(cka_ id) +
  1976                             "]");
  1977                    }
  1978                    retu rn false;
  1979                }
  1980  
  1981                X509Cert ificate en dCert = lo adCert(ses sion, h.ha ndle);
  1982                token.p1 1.C_Destro yObject(se ssion.id() , h.handle );
  1983                if (debu g != null)  {
  1984                    debu g.println( "destroyCh ain destro yed end en tity cert  " +
  1985                             "with  CKA_ID ["  +
  1986                             getID( cka_id) +
  1987                             "]");
  1988                }
  1989  
  1990                // build  chain fol lowing iss uer->subje ct links
  1991  
  1992                X509Cert ificate ne xt = endCe rt;
  1993                while (t rue) {
  1994  
  1995                    if ( next.getSu bjectX500P rincipal() .equals
  1996                         (next.getI ssuerX500P rincipal() )) {
  1997                         // self si gned - don e
  1998                         break;
  1999                    }
  2000  
  2001                    CK_A TTRIBUTE[]  attrs = n ew CK_ATTR IBUTE[] {
  2002                             ATTR_T OKEN_TRUE,
  2003                             ATTR_C LASS_CERT,
  2004                             new CK _ATTRIBUTE (CKA_SUBJE CT,
  2005                                        next.g etIssuerX5 00Principa l().getEnc oded()) };
  2006                    long [] ch = fi ndObjects( session, a ttrs);
  2007  
  2008                    if ( ch == null  || ch.len gth == 0)  {
  2009                         // done
  2010                         break;
  2011                    } el se {
  2012                         // if more  than one  found, use  first
  2013                         if (debug  != null &&  ch.length  > 1) {
  2014                             debug. println("d estroyChai n found "  +
  2015                                      ch.lengt h +
  2016                                      " certif icate entr ies for su bject [" +
  2017                                      next.get IssuerX500 Principal( ) +
  2018                                      "] in to ken - usin g first en try");
  2019                         }
  2020  
  2021                         next = loa dCert(sess ion, ch[0] );
  2022  
  2023                         // only de lete if no t part of  any other  chain
  2024  
  2025                         attrs = ne w CK_ATTRI BUTE[] {
  2026                             ATTR_T OKEN_TRUE,
  2027                             ATTR_C LASS_CERT,
  2028                             new CK _ATTRIBUTE (CKA_ISSUE R,
  2029                                      next.get SubjectX50 0Principal ().getEnco ded()) };
  2030                         long[] iss uers = fin dObjects(s ession, at trs);
  2031  
  2032                         boolean de stroyIt =  false;
  2033                         if (issuer s == null  || issuers .length ==  0) {
  2034                             // no  other cert s with thi s issuer -
  2035                             // des troy it
  2036                             destro yIt = true ;
  2037                         } else if  (issuers.l ength == 1 ) {
  2038                             X509Ce rtificate  iCert = lo adCert(ses sion, issu ers[0]);
  2039                             if (ne xt.equals( iCert)) {
  2040                                 //  only cert  with issu er is itse lf (self-s igned) -
  2041                                 //  destroy i t
  2042                                 de stroyIt =  true;
  2043                             }
  2044                         }
  2045  
  2046                         if (destro yIt) {
  2047                             token. p11.C_Dest royObject( session.id (), ch[0]) ;
  2048                             if (de bug != nul l) {
  2049                                 de bug.printl n
  2050                                      ("destro yChain des troyed cer t in chain  " +
  2051                                      "with su bject [" +
  2052                                      next.get SubjectX50 0Principal () + "]");
  2053                             }
  2054                         } else {
  2055                             if (de bug != nul l) {
  2056                                 de bug.printl n("destroy Chain did  not destro y " +
  2057                                      "shared  cert in ch ain with s ubject ["  +
  2058                                      next.get SubjectX50 0Principal () + "]");
  2059                             }
  2060                         }
  2061                    }
  2062                }
  2063  
  2064                return t rue;
  2065  
  2066           }  finally {
  2067                token.re leaseSessi on(session );
  2068           }
  2069       }
  2070  
  2071       /**
  2072          * return t rue if  PW        key destro yed
  2073        */
  2074       privat e boolean  destroySke y(String a lias)
  2075                    thro ws PKCS11E xception,  KeyStoreEx ception {
  2076           Se ssion sess ion = null ;
  2077           tr y {
  2078                session  = token.ge tOpSession ();
  2079  
  2080                THandle  h = getTok enObject(s ession, AT TR_CLASS_S KEY, null,  alias);
  2081                if (h.ty pe != ATTR _CLASS_SKE Y) {
  2082                    if ( debug != n ull) {
  2083                          debug.prin tln("destr oySkey did  not find  PW        key " +
  2084                             "with  CKA_LABEL  [" +
  2085                             alias  +
  2086                             "]");
  2087                    }
  2088                    retu rn false;
  2089                }
  2090                token.p1 1.C_Destro yObject(se ssion.id() , h.handle );
  2091                return t rue;
  2092           }  finally {
  2093                token.re leaseSessi on(session );
  2094           }
  2095       }
  2096  
  2097       /**
  2098        * ret urn true i f private  key destro yed
  2099        */
  2100       privat e boolean  destroyPke y(byte[] c ka_id)
  2101                    thro ws PKCS11E xception,  KeyStoreEx ception {
  2102           Se ssion sess ion = null ;
  2103           tr y {
  2104                session  = token.ge tOpSession ();
  2105  
  2106                THandle  h = getTok enObject(s ession, AT TR_CLASS_P KEY, cka_i d, null);
  2107                if (h.ty pe != ATTR _CLASS_PKE Y) {
  2108                    if ( debug != n ull) {
  2109                         debug.prin tln
  2110                             ("dest royPkey di d not find  private k ey with CK A_ID [" +
  2111                             getID( cka_id) +
  2112                             "]");
  2113                    }
  2114                    retu rn false;
  2115                }
  2116                token.p1 1.C_Destro yObject(se ssion.id() , h.handle );
  2117                return t rue;
  2118           }  finally {
  2119                token.re leaseSessi on(session );
  2120           }
  2121       }
  2122  
  2123       /**
  2124        * bui ld [alias  + issuer +  serialNum ber] strin g from a c ert
  2125        */
  2126       privat e String g etID(Strin g alias, X 509Certifi cate cert)  {
  2127           X5 00Principa l issuer =  cert.getI ssuerX500P rincipal() ;
  2128           Bi gInteger s erialNum =  cert.getS erialNumbe r();
  2129  
  2130           re turn alias  +
  2131                    ALIA S_SEP +
  2132                    issu er.getName (X500Princ ipal.CANON ICAL) +
  2133                    ALIA S_SEP +
  2134                    seri alNum.toSt ring();
  2135       }
  2136  
  2137       /**
  2138        * bui ld CKA_ID  string fro m bytes
  2139        */
  2140       privat e static S tring getI D(byte[] b ytes) {
  2141           bo olean prin table = tr ue;
  2142           fo r (int i =  0; i < by tes.length ; i++) {
  2143                if (!Der Value.isPr intableStr ingChar((c har)bytes[ i])) {
  2144                    prin table = fa lse;
  2145                    brea k;
  2146                }
  2147           }
  2148  
  2149           if  (!printab le) {
  2150                return " 0x" + Func tions.toHe xString(by tes);
  2151           }  else {
  2152                try {
  2153                    retu rn new Str ing(bytes,  "UTF-8");
  2154                } catch  (Unsupport edEncoding Exception  uee) {
  2155                    retu rn "0x" +  Functions. toHexStrin g(bytes);
  2156                }
  2157           }
  2158       }
  2159  
  2160       /**
  2161        * fin d an objec t on the t oken
  2162        *
  2163        * @pa ram type e ither ATTR _CLASS_CER T, ATTR_CL ASS_PKEY,  or ATTR_CL ASS_SKEY
  2164        * @pa ram cka_id  the CKA_I D if type  is ATTR_CL ASS_CERT o r ATTR_CLA SS_PKEY
  2165        * @pa ram cka_la bel the CK A_LABEL if  type is A TTR_CLASS_ SKEY
  2166        */
  2167       privat e THandle  getTokenOb ject(Sessi on session ,
  2168                                      CK_ATTRI BUTE type,
  2169                                      byte[] c ka_id,
  2170                                      String c ka_label)
  2171                    thro ws PKCS11E xception,  KeyStoreEx ception {
  2172  
  2173           CK _ATTRIBUTE [] attrs;
  2174           if  (type ==  ATTR_CLASS _SKEY) {
  2175                attrs =  new CK_ATT RIBUTE[] {
  2176                             ATTR_S KEY_TOKEN_ TRUE,
  2177                             new CK _ATTRIBUTE (CKA_LABEL , cka_labe l),
  2178                             type } ;
  2179           }  else {
  2180                attrs =  new CK_ATT RIBUTE[] {
  2181                             ATTR_T OKEN_TRUE,
  2182                             new CK _ATTRIBUTE (CKA_ID, c ka_id),
  2183                             type } ;
  2184           }
  2185           lo ng[] h = f indObjects (session,  attrs);
  2186           if  (h.length  == 0) {
  2187                if (debu g != null)  {
  2188                    if ( type == AT TR_CLASS_S KEY) {
  2189                          debug.prin tln("getTo kenObject  did not fi nd  PW        key " +
  2190                                      "with CK A_LABEL ["  +
  2191                                      cka_labe l +
  2192                                      "]");
  2193                    } el se if (typ e == ATTR_ CLASS_CERT ) {
  2194                         debug.prin tln
  2195                             ("getT okenObject  did not f ind cert w ith CKA_ID  [" +
  2196                             getID( cka_id) +
  2197                             "]");
  2198                    } el se {
  2199                         debug.prin tln("getTo kenObject  did not fi nd private  key " +
  2200                             "with  CKA_ID ["  +
  2201                             getID( cka_id) +
  2202                             "]");
  2203                    }
  2204                }
  2205           }  else if (h .length ==  1) {
  2206  
  2207                // found  object ha ndle - ret urn it
  2208                return n ew THandle (h[0], typ e);
  2209  
  2210           }  else {
  2211  
  2212                // found  multiple  object han dles -
  2213                // see i f token ig nored CKA_ LABEL duri ng search  (e.g. NSS)
  2214  
  2215                if (type  == ATTR_C LASS_SKEY)  {
  2216  
  2217                    Arra yList<THan dle> list  = new Arra yList<THan dle>(h.len gth);
  2218                    for  (int i = 0 ; i < h.le ngth; i++)  {
  2219  
  2220                         CK_ATTRIBU TE[] label  = new CK_ ATTRIBUTE[ ]
  2221                                               { new CK_A TTRIBUTE(C KA_LABEL)  };
  2222                         token.p11. C_GetAttri buteValue( session.id (), h[i],  label);
  2223                         if (label[ 0].pValue  != null &&
  2224                             cka_la bel.equals (new Strin g(label[0] .getCharAr ray()))) {
  2225                             list.a dd(new THa ndle(h[i],  ATTR_CLAS S_SKEY));
  2226                         }
  2227                    }
  2228                    if ( list.size( ) == 1) {
  2229                         // yes, th ere was on ly one CKA _LABEL tha t matched
  2230                         return lis t.get(0);
  2231                    } el se {
  2232                         throw new  KeyStoreEx ception("i nvalid Key Store stat e: " +
  2233                             "found  " +
  2234                             list.s ize() +
  2235                               PW        keys shari ng CKA_LAB EL [" +
  2236                             cka_la bel +
  2237                             "]");
  2238                    }
  2239                } else i f (type ==  ATTR_CLAS S_CERT) {
  2240                    thro w new KeyS toreExcept ion("inval id KeyStor e state: "  +
  2241                             "found  " +
  2242                             h.leng th +
  2243                             " cert ificates s haring CKA _ID " +
  2244                             getID( cka_id));
  2245                } else {
  2246                    thro w new KeyS toreExcept ion("inval id KeyStor e state: "  +
  2247                             "found  " +
  2248                             h.leng th +
  2249                             " priv ate keys s haring CKA _ID " +
  2250                             getID( cka_id));
  2251                }
  2252           }
  2253           re turn new T Handle(NO_ HANDLE, nu ll);
  2254       }
  2255  
  2256       /**
  2257          * Create a  mapping o f all key  pairs, tru sted certs , and  PW        keys
  2258        * on  the token  into logic al KeyStor e entries  unambiguou sly
  2259        * acc essible vi a an alias .
  2260        *
  2261        * If  the token  is removed , the map  may contai n stale va lues.
  2262        * Key Store.load  should be  called to  re-create  the map.
  2263        *
  2264        * Ass ume all pr ivate keys  and match ing certs  share a un ique CKA_I D.
  2265        *
  2266          * Assume a ll  PW        keys have  a unique C KA_LABEL.
  2267        *
  2268        * @re turn true  if multipl e certs fo und sharin g the same  CKA_LABEL
  2269        *           (if  so, write  capabiliti es are dis abled)
  2270        */
  2271       privat e boolean  mapLabels( ) throws
  2272                    PKCS 11Exceptio n, Certifi cateExcept ion, KeySt oreExcepti on {
  2273  
  2274           CK _ATTRIBUTE [] trusted Attr = new  CK_ATTRIB UTE[] {
  2275                                      new CK_A TTRIBUTE(C KA_TRUSTED ) };
  2276  
  2277           Se ssion sess ion = null ;
  2278           tr y {
  2279                session  = token.ge tOpSession ();
  2280  
  2281                // get a ll private  key CKA_I Ds
  2282  
  2283                ArrayLis t<byte[]>  pkeyIDs =  new ArrayL ist<byte[] >();
  2284                CK_ATTRI BUTE[] att rs = new C K_ATTRIBUT E[] {
  2285                    ATTR _TOKEN_TRU E,
  2286                    ATTR _CLASS_PKE Y,
  2287                };
  2288                long[] h andles = f indObjects (session,  attrs);
  2289  
  2290                for (lon g handle :  handles)  {
  2291                    attr s = new CK _ATTRIBUTE [] { new C K_ATTRIBUT E(CKA_ID)  };
  2292                    toke n.p11.C_Ge tAttribute Value(sess ion.id(),  handle, at trs);
  2293  
  2294                    if ( attrs[0].p Value != n ull) {
  2295                         pkeyIDs.ad d(attrs[0] .getByteAr ray());
  2296                    }
  2297                }
  2298  
  2299                // Get a ll certifi cates
  2300                //
  2301                // If ce rt does no t have a C KA_LABEL n or CKA_ID,  it is ign ored.
  2302                //
  2303                // Get t he CKA_LAB EL for eac h cert
  2304                // (if t he cert do es not hav e a CKA_LA BEL, use t he CKA_ID) .
  2305                //
  2306                // Map e ach cert t o the its  CKA_LABEL
  2307                // (mult iple certs  may be ma pped to a  single CKA _LABEL)
  2308  
  2309                HashMap< String, Ha shSet<Alia sInfo>> ce rtMap =
  2310                                      new Hash Map<String , HashSet< AliasInfo> >();
  2311  
  2312                attrs =  new CK_ATT RIBUTE[] {
  2313                    ATTR _TOKEN_TRU E,
  2314                    ATTR _CLASS_CER T,
  2315                };
  2316                handles  = findObje cts(sessio n, attrs);
  2317  
  2318                for (lon g handle :  handles)  {
  2319                    attr s = new CK _ATTRIBUTE [] { new C K_ATTRIBUT E(CKA_LABE L) };
  2320  
  2321                    Stri ng cka_lab el = null;
  2322                    byte [] cka_id  = null;
  2323                    try  {
  2324                         token.p11. C_GetAttri buteValue( session.id (), handle , attrs);
  2325                         if (attrs[ 0].pValue  != null) {
  2326                             // the re is a CK A_LABEL
  2327                             cka_la bel = new  String(att rs[0].getC harArray() );
  2328                         }
  2329                    } ca tch (PKCS1 1Exception  pe) {
  2330                         if (pe.get ErrorCode( ) != CKR_A TTRIBUTE_T YPE_INVALI D) {
  2331                             throw  pe;
  2332                         }
  2333  
  2334                         // GetAttr ibuteValue  for CKA_L ABEL not s upported
  2335                         //
  2336                         // XXX SCA 1000
  2337                    }
  2338  
  2339                    // g et CKA_ID
  2340  
  2341                    attr s = new CK _ATTRIBUTE [] { new C K_ATTRIBUT E(CKA_ID)  };
  2342                    toke n.p11.C_Ge tAttribute Value(sess ion.id(),  handle, at trs);
  2343                    if ( attrs[0].p Value == n ull) {
  2344                         if (cka_la bel == nul l) {
  2345                             // no  cka_label  nor cka_id  - ignore
  2346                             contin ue;
  2347                         }
  2348                    } el se {
  2349                         if (cka_la bel == nul l) {
  2350                             // use  CKA_ID as  CKA_LABEL
  2351                             cka_la bel = getI D(attrs[0] .getByteAr ray());
  2352                         }
  2353                         cka_id = a ttrs[0].ge tByteArray ();
  2354                    }
  2355  
  2356                    X509 Certificat e cert = l oadCert(se ssion, han dle);
  2357  
  2358                    // g et CKA_TRU STED
  2359  
  2360                    bool ean cka_tr usted = fa lse;
  2361  
  2362                    if ( useSecmodT rust) {
  2363                         cka_truste d = Secmod .getInstan ce().isTru sted(cert,  nssTrustT ype);
  2364                    } el se {
  2365                         if (CKA_TR USTED_SUPP ORTED) {
  2366                             try {
  2367                                 to ken.p11.C_ GetAttribu teValue
  2368                                          (ses sion.id(),  handle, t rustedAttr );
  2369                                 ck a_trusted  = trustedA ttr[0].get Boolean();
  2370                             } catc h (PKCS11E xception p e) {
  2371                                 if  (pe.getEr rorCode()  == CKR_ATT RIBUTE_TYP E_INVALID)  {
  2372                                      // XXX   NSS, ibutt on, sca100 0
  2373                                      CKA_TRUS TED_SUPPOR TED = fals e;
  2374                                      if (debu g != null)  {
  2375                                          debu g.println
  2376                                                   ("CKA_ TRUSTED at tribute no t supporte d");
  2377                                      }
  2378                                 }
  2379                             }
  2380                         }
  2381                    }
  2382  
  2383                    Hash Set<AliasI nfo> infoS et = certM ap.get(cka _label);
  2384                    if ( infoSet ==  null) {
  2385                         infoSet =  new HashSe t<AliasInf o>(2);
  2386                         certMap.pu t(cka_labe l, infoSet );
  2387                    }
  2388  
  2389                    // i nitially c reate priv ate key en try AliasI nfo entrie s -
  2390                    // t hese entri es will ge t resolved  into thei r true
  2391                    // e ntry types  later
  2392  
  2393                    info Set.add(ne w AliasInf o
  2394                                      (cka_lab el,
  2395                                      cka_id,
  2396                                      cka_trus ted,
  2397                                      cert));
  2398                }
  2399  
  2400                  // create  list  PW        key CKA_LA BELS -
  2401                  // if ther e are dupl icates (ei ther betwe en  PW        keys,
  2402                  // or betw een a  PW        key and an other obje ct),
  2403                // throw  an except ion
  2404                HashMap< String, Al iasInfo> s KeyMap =
  2405                         new HashMa p<String,  AliasInfo> ();
  2406  
  2407                attrs =  new CK_ATT RIBUTE[] {
  2408                    ATTR _SKEY_TOKE N_TRUE,
  2409                    ATTR _CLASS_SKE Y,
  2410                };
  2411                handles  = findObje cts(sessio n, attrs);
  2412  
  2413                for (lon g handle :  handles)  {
  2414                    attr s = new CK _ATTRIBUTE [] { new C K_ATTRIBUT E(CKA_LABE L) };
  2415                    toke n.p11.C_Ge tAttribute Value(sess ion.id(),  handle, at trs);
  2416                    if ( attrs[0].p Value != n ull) {
  2417  
  2418                         // there i s a CKA_LA BEL
  2419                         String cka _label = n ew String( attrs[0].g etCharArra y());
  2420                         if (sKeyMa p.get(cka_ label) ==  null) {
  2421                             sKeyMa p.put(cka_ label, new  AliasInfo (cka_label ));
  2422                         } else {
  2423                             throw  new KeySto reExceptio n("invalid  KeyStore  state: " +
  2424                                        "found mul tiple  PW        keys shari ng same "  +
  2425                                      "CKA_LAB EL [" +
  2426                                      cka_labe l +
  2427                                      "]");
  2428                         }
  2429                    }
  2430                }
  2431  
  2432                // updat e global a liasMap wi th alias m appings
  2433                ArrayLis t<AliasInf o> matched Certs =
  2434                                      mapPriva teKeys(pke yIDs, cert Map);
  2435                boolean  sharedLabe l = mapCer ts(matched Certs, cer tMap);
  2436                mapSecre tKeys(sKey Map);
  2437  
  2438                return s haredLabel ;
  2439  
  2440           }  finally {
  2441                token.re leaseSessi on(session );
  2442           }
  2443       }
  2444  
  2445       /**
  2446        * for  each priv ate key CK A_ID, find  correspon ding cert  with same  CKA_ID.
  2447        * if  found cert , see if c ert CKA_LA BEL is uni que.
  2448        *      if CKA_LA BEL unique , map priv ate key/ce rt alias t o that CKA _LABEL.
  2449        *      if CKA_LA BEL not un ique, map  private ke y/cert ali as to:
  2450        *                     CKA_L ABEL + ALI AS_SEP + I SSUER + AL IAS_SEP +  SERIAL
  2451        * if  cert not f ound, igno re private  key
  2452        * (do n't suppor t private  key entrie s without  a cert cha in yet)
  2453        *
  2454        * @re turn a lis t of Alias Info entri es that re presents a ll matches
  2455        */
  2456       privat e ArrayLis t<AliasInf o> mapPriv ateKeys(Ar rayList<by te[]> pkey IDs,
  2457                             HashMa p<String,  HashSet<Al iasInfo>>  certMap)
  2458                    thro ws PKCS11E xception,  Certificat eException  {
  2459  
  2460           //  reset glo bal alias  map
  2461           al iasMap = n ew HashMap <String, A liasInfo>( );
  2462  
  2463           //  list of m atched cer ts that we  will retu rn
  2464           Ar rayList<Al iasInfo> m atchedCert s = new Ar rayList<Al iasInfo>() ;
  2465  
  2466           fo r (byte[]  pkeyID : p keyIDs) {
  2467  
  2468                // try t o find a m atching CK A_ID in a  certificat e
  2469  
  2470                boolean  foundMatch  = false;
  2471                Set<Stri ng> certLa bels = cer tMap.keySe t();
  2472                for (Str ing certLa bel : cert Labels) {
  2473  
  2474                    // g et cert CK A_IDs (if  present) f or each ce rt
  2475  
  2476                    Hash Set<AliasI nfo> infoS et = certM ap.get(cer tLabel);
  2477                    for  (AliasInfo  aliasInfo  : infoSet ) {
  2478                         if (Arrays .equals(pk eyID, alia sInfo.id))  {
  2479  
  2480                             // fou nd private  key with  matching c ert
  2481  
  2482                             if (in foSet.size () == 1) {
  2483                                 //  unique CK A_LABEL -  use certLa bel as ali as
  2484                                 al iasInfo.ma tched = tr ue;
  2485                                 al iasMap.put (certLabel , aliasInf o);
  2486                             } else  {
  2487                                 //  create ne w alias
  2488                                 al iasInfo.ma tched = tr ue;
  2489                                 al iasMap.put (getID(cer tLabel, al iasInfo.ce rt),
  2490                                               aliasInfo) ;
  2491                             }
  2492                             matche dCerts.add (aliasInfo );
  2493                             foundM atch = tru e;
  2494                             break;
  2495                         }
  2496                    }
  2497                    if ( foundMatch ) {
  2498                         break;
  2499                    }
  2500                }
  2501  
  2502                if (!fou ndMatch) {
  2503                    if ( debug != n ull) {
  2504                         debug.prin tln
  2505                             ("did  not find m atch for p rivate key  with CKA_ ID [" +
  2506                             getID( pkeyID) +
  2507                             "] (ig noring ent ry)");
  2508                    }
  2509                }
  2510           }
  2511  
  2512           re turn match edCerts;
  2513       }
  2514  
  2515       /**
  2516        * for  each cert  not match ed with a  private ke y but is C KA_TRUSTED :
  2517        *      if CKA_LA BEL unique , map cert  to CKA_LA BEL.
  2518        *      if CKA_LA BEL not un ique, map  cert to [l abel+issue r+serialNu m]
  2519        *
  2520        * if  CKA_TRUSTE D not supp orted, tre at all cer ts not par t of a cha in
  2521        * as  trusted
  2522        *
  2523        * @re turn true  if multipl e certs fo und sharin g the same  CKA_LABEL
  2524        */
  2525       privat e boolean  mapCerts(A rrayList<A liasInfo>  matchedCer ts,
  2526                             HashMa p<String,  HashSet<Al iasInfo>>  certMap)
  2527                    thro ws PKCS11E xception,  Certificat eException  {
  2528  
  2529           //  load all  cert chain s
  2530           fo r (AliasIn fo aliasIn fo : match edCerts) {
  2531                Session  session =  null;
  2532                try {
  2533                    sess ion = toke n.getOpSes sion();
  2534                    alia sInfo.chai n = loadCh ain(sessio n, aliasIn fo.cert);
  2535                } finall y {
  2536                    toke n.releaseS ession(ses sion);
  2537                }
  2538           }
  2539  
  2540           //  find all  certs in c ertMap not  part of a  cert chai n
  2541           //  - these a re trusted
  2542  
  2543           bo olean shar edLabel =  false;
  2544  
  2545           Se t<String>  certLabels  = certMap .keySet();
  2546           fo r (String  certLabel  : certLabe ls) {
  2547                HashSet< AliasInfo>  infoSet =  certMap.g et(certLab el);
  2548                for (Ali asInfo ali asInfo : i nfoSet) {
  2549  
  2550                    if ( aliasInfo. matched ==  true) {
  2551                         // already  found a p rivate key  match for  this cert  -
  2552                         // just co ntinue
  2553                         aliasInfo. trusted =  false;
  2554                         continue;
  2555                    }
  2556  
  2557                    // c ert in thi s aliasInf o is not m atched yet
  2558                    //
  2559                    // i f CKA_TRUS TED_SUPPOR TED == tru e,
  2560                    // t hen check  if cert is  trusted
  2561  
  2562                    if ( CKA_TRUSTE D_SUPPORTE D) {
  2563                         if (aliasI nfo.truste d) {
  2564                             // tru sted certi ficate
  2565                             if (ma pTrustedCe rt
  2566                                      (certLab el, aliasI nfo, infoS et) == tru e) {
  2567                                 sh aredLabel  = true;
  2568                             }
  2569                         }
  2570                         continue;
  2571                    }
  2572  
  2573                    // C KA_TRUSTED _SUPPORTED  == false
  2574                    //
  2575                    // X XX treat a ll certs n ot part of  a chain a s trusted
  2576                    // X XX
  2577                    // X XX Unsuppo rted
  2578                    //
  2579                    // b oolean par tOfChain =  false;
  2580                    // f or (AliasI nfo matche dInfo : ma tchedCerts ) {
  2581                    //      for (in t i = 0; i  < matched Info.chain .length; i ++) {
  2582                    //       if (ma tchedInfo. chain[i].e quals(alia sInfo.cert )) {
  2583                    //           pa rtOfChain  = true;
  2584                    //           br eak;
  2585                    //       }
  2586                    //      }
  2587                    //      if (par tOfChain)  {
  2588                    //       break;
  2589                    //      }
  2590                    // }
  2591                    //
  2592                    // i f (!partOf Chain) {
  2593                    //      if (map TrustedCer t(certLabe l,aliasInf o,infoSet)  == true){
  2594                    //       shared Label = tr ue;
  2595                    //      }
  2596                    // }  else {
  2597                    //     if (debu g != null)  {
  2598                    //       debug. println("i gnoring un matched/un trusted ce rt " +
  2599                    //           "t hat is par t of cert  chain - ce rt subject  is [" +
  2600                    //           al iasInfo.ce rt.getSubj ectX500Pri ncipal().g etName
  2601                    //                                 (X 500Princip al.CANONIC AL) +
  2602                    //           "] ");
  2603                    //      }
  2604                    // }
  2605                }
  2606           }
  2607  
  2608           re turn share dLabel;
  2609       }
  2610  
  2611       privat e boolean  mapTrusted Cert(Strin g certLabe l,
  2612                                      AliasInf o aliasInf o,
  2613                                      HashSet< AliasInfo>  infoSet)  {
  2614  
  2615           bo olean shar edLabel =  false;
  2616  
  2617           al iasInfo.ty pe = ATTR_ CLASS_CERT ;
  2618           al iasInfo.tr usted = tr ue;
  2619           if  (infoSet. size() ==  1) {
  2620                // uniqu e CKA_LABE L - use ce rtLabel as  alias
  2621                aliasMap .put(certL abel, alia sInfo);
  2622           }  else {
  2623                // creat e new alia s
  2624                sharedLa bel = true ;
  2625                aliasMap .put(getID (certLabel , aliasInf o.cert), a liasInfo);
  2626           }
  2627  
  2628           re turn share dLabel;
  2629       }
  2630  
  2631       /**
  2632          * If the  PW        key shares  a CKA_LAB EL with an other entr y,
  2633        * thr ow an exce ption
  2634        */
  2635       privat e void map SecretKeys (HashMap<S tring, Ali asInfo> sK eyMap)
  2636                    thro ws KeyStor eException  {
  2637           fo r (String  label : sK eyMap.keyS et()) {
  2638                if (alia sMap.conta insKey(lab el)) {
  2639                    thro w new KeyS toreExcept ion("inval id KeyStor e state: "  +
  2640                               "found  PW        key sharin g CKA_LABE L [" +
  2641                             label  +
  2642                             "] wit h another  token obje ct");
  2643                }
  2644           }
  2645           al iasMap.put All(sKeyMa p);
  2646       }
  2647  
  2648       privat e void dum pTokenMap( ) {
  2649           Se t<String>  aliases =  aliasMap.k eySet();
  2650           Sy stem.out.p rintln("To ken Alias  Map:");
  2651           if  (aliases. isEmpty())  {
  2652                System.o ut.println ("  [empty ]");
  2653           }  else {
  2654                for (Str ing s : al iases) {
  2655                    Syst em.out.pri ntln("  "  + s + alia sMap.get(s ));
  2656                }
  2657           }
  2658       }
  2659  
  2660       privat e void che ckWrite()  throws Key StoreExcep tion {
  2661           if  (writeDis abled) {
  2662                throw ne w KeyStore Exception
  2663                    ("Th is PKCS11K eyStore do es not sup port write  capabilit ies");
  2664           }
  2665       }
  2666  
  2667       privat e final st atic long[ ] LONG0 =  new long[0 ];
  2668  
  2669       privat e static l ong[] find Objects(Se ssion sess ion, CK_AT TRIBUTE[]  attrs)
  2670                throws P KCS11Excep tion {
  2671           To ken token  = session. token;
  2672           lo ng[] handl es = LONG0 ;
  2673           to ken.p11.C_ FindObject sInit(sess ion.id(),  attrs);
  2674           wh ile (true)  {
  2675                long[] h  = token.p 11.C_FindO bjects(ses sion.id(),  FINDOBJEC TS_MAX);
  2676                if (h.le ngth == 0)  {
  2677                    brea k;
  2678                }
  2679                handles  = P11Util. concat(han dles, h);
  2680           }
  2681           to ken.p11.C_ FindObject sFinal(ses sion.id()) ;
  2682           re turn handl es;
  2683       }
  2684  
  2685   }