001    // Copyright (C) 2002 IAIK
002    // https://jce.iaik.tugraz.at
003    //
004    // Copyright (C) 2003 - 2025 Stiftung Secure Information and
005    //                           Communication Technologies SIC
006    // https://sic.tech
007    //
008    // All rights reserved.
009    //
010    // Redistribution and use in source and binary forms, with or without
011    // modification, are permitted provided that the following conditions
012    // are met:
013    // 1. Redistributions of source code must retain the above copyright
014    //    notice, this list of conditions and the following disclaimer.
015    // 2. Redistributions in binary form must reproduce the above copyright
016    //    notice, this list of conditions and the following disclaimer in the
017    //    documentation and/or other materials provided with the distribution.
018    //
019    // THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
020    // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
021    // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
022    // ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
023    // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
024    // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
025    // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
026    // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
027    // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
028    // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
029    // SUCH DAMAGE.
030    
031    // Copyright (C) 2002 IAIK
032    // https://sic.tech/
033    //
034    // Copyright (C) 2003 - 2025 Stiftung Secure Information and 
035    //                           Communication Technologies SIC
036    // https://sic.tech/
037    //
038    // All rights reserved.
039    //
040    // This source is provided for inspection purposes and recompilation only,
041    // unless specified differently in a contract with IAIK. This source has to
042    // be kept in strict confidence and must not be disclosed to any third party
043    // under any circumstances. Redistribution in source and binary forms, with
044    // or without modification, are <not> permitted in any case!
045    //
046    // THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
047    // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
048    // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
049    // ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
050    // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
051    // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
052    // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
053    // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
054    // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
055    // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
056    // SUCH DAMAGE.
057    //
058    // $Header: /IAIK-CMS/current/src/demo/keystore/SetupCMSKeyStore.java 42    12.02.25 17:58 Dbratko $
059    // $Revision: 42 $
060    //
061    
062    package demo.keystore;
063    
064    import iaik.asn1.CodingException;
065    import iaik.asn1.ObjectID;
066    import iaik.asn1.structures.AlgorithmID;
067    import iaik.asn1.structures.GeneralName;
068    import iaik.asn1.structures.GeneralNames;
069    import iaik.asn1.structures.Name;
070    import iaik.asn1.structures.PolicyInformation;
071    import iaik.asn1.structures.PolicyQualifierInfo;
072    import iaik.cms.SecurityProvider;
073    import iaik.cms.Utils;
074    import iaik.pkcs.pkcs1.MGF1ParameterSpec;
075    import iaik.pkcs.pkcs1.MaskGenerationAlgorithm;
076    import iaik.pkcs.pkcs1.RSAPssParameterSpec;
077    import iaik.security.rsa.RSAPssKeyPairGenerator;
078    import iaik.x509.SimpleChainVerifier;
079    import iaik.x509.X509Certificate;
080    import iaik.x509.X509ExtensionException;
081    import iaik.x509.extensions.AuthorityKeyIdentifier;
082    import iaik.x509.extensions.BasicConstraints;
083    import iaik.x509.extensions.CertificatePolicies;
084    import iaik.x509.extensions.ExtendedKeyUsage;
085    import iaik.x509.extensions.KeyUsage;
086    import iaik.x509.extensions.SubjectAltName;
087    import iaik.x509.extensions.SubjectKeyIdentifier;
088    
089    import java.io.BufferedReader;
090    import java.io.File;
091    import java.io.FileInputStream;
092    import java.io.FileOutputStream;
093    import java.io.IOException;
094    import java.io.InputStreamReader;
095    import java.math.BigInteger;
096    import java.security.InvalidAlgorithmParameterException;
097    import java.security.InvalidKeyException;
098    import java.security.KeyPair;
099    import java.security.KeyPairGenerator;
100    import java.security.KeyStore;
101    import java.security.KeyStoreException;
102    import java.security.MessageDigest;
103    import java.security.NoSuchAlgorithmException;
104    import java.security.NoSuchProviderException;
105    import java.security.PrivateKey;
106    import java.security.PublicKey;
107    import java.security.cert.CertificateException;
108    import java.util.Calendar;
109    import java.util.GregorianCalendar;
110    import java.util.Random;
111    
112    import demo.DemoUtil;
113    
114    
115    /**
116     * Creates a default KeyStore in the current working directory.
117     * These keys are used by many demos included in IAIK-JCE.
118     * The aliases and the password for accessing the keys and
119     * certificates can be found in {@link demo.keystore.CMSKeyStoreConstants CMSKeyStoreConstants}.
120     *
121     * @see CMSKeyStoreConstants
122     */
123    public class SetupCMSKeyStore implements CMSKeyStoreConstants {
124    
125      // the keylength of the CA certificate shall be 1024
126      private final static int CA_KEYLENGTH = 2048;
127    
128      // the key store to create
129      KeyStore key_store;
130      // the file where the key store shall be saved
131      String keystore_file;
132      // takes the existing keys from the KeyStore and only creates new certificates
133      boolean create_only_certificates = true;
134    
135      // the private keys
136      
137      // CA keys
138      KeyPair ca_dsa = null;
139      KeyPair ca_rsa = null;
140      KeyPair ca_rsa_pss = null;
141      
142      // RSA for signing
143      KeyPair rsa2048_sign_1 = null;
144      KeyPair rsa2048_sign_2 = null;
145      KeyPair rsa2048_sign_3 = null;
146      // RSA for encrypting
147      KeyPair rsa2048_crypt_1 = null;
148      KeyPair rsa2048_crypt_2 = null;
149      KeyPair rsa2048_crypt_3 = null;
150      // RSA-PSS for signing
151      KeyPair rsapss2048_sha1_sign = null;
152      KeyPair rsapss2048_sha256_sign = null;
153      KeyPair rsapss2048_sha384_sign = null;
154      KeyPair rsapss2048_sha512_sign = null;
155    
156      // DSA signing
157      KeyPair dsa1024 = null;
158      // DSA with SHA224
159      KeyPair dsa2048 = null;
160      // DSA with SHA256
161      KeyPair dsa3072 = null;
162      
163      // DH key exchange
164      KeyPair esdh2048_1 = null;
165      KeyPair esdh2048_2 = null;
166      KeyPair ssdh2048_1 = null;
167      KeyPair ssdh2048_2 = null;
168      
169      // TSP Server
170      KeyPair tsp_server = null;
171    
172      // create RSA keys and certificates
173      boolean create_rsa;
174      // create RSA-PSS key and certificates
175      boolean create_rsa_pss;
176      // create DSA keys and certificates
177      boolean create_dsa;
178      // create DSA SHA-2 keys and certificates
179      boolean create_dsa_sha2;
180      // create ESDH keys and certificates
181      boolean create_esdh;
182      // create SSDH keys and certificates
183      boolean create_ssdh;
184      // create TSP server key and certificate
185      boolean create_tspserver;
186    
187      /**
188       * The KeyStore file name.
189       */
190      String ks_filename = KS_FILENAME;
191      
192      
193      /**
194       * Default Constructor.
195       */
196      public SetupCMSKeyStore() {
197        this(KS_FILENAME);
198      } 
199      
200      /**
201       * Creates a SetupCMSKeyStore for the given keystore filename.
202       * 
203       * @param ksFileName the KeyStore filename
204       */
205      public SetupCMSKeyStore(String ksFileName) {
206        ks_filename = ksFileName;
207        create_rsa = true;
208        create_rsa_pss = true;
209        create_dsa = true;
210        create_dsa_sha2 = ((create_dsa) && (Utils.getIaikProviderVersion() >= 3.18));
211        create_esdh = create_ssdh = Utils.isClassAvailable("iaik.security.dh.ESDHPublicKey");
212        create_tspserver = true;
213    
214      } 
215    
216      /**
217       * Generate a KeyPair using the specified algorithm with the given size.
218       *
219       * @param algorithm the algorithm to use
220       * @param bits the length of the key (modulus) in bits
221       * @return the KeyPair
222       */
223      private static KeyPair generateKeyPair(String algorithm, int bits) 
224            throws NoSuchAlgorithmException {
225    
226            KeyPairGenerator generator = null;
227        try {
228              generator = KeyPairGenerator.getInstance(algorithm, "IAIK"); 
229            } catch (NoSuchProviderException ex) {
230              throw new NoSuchAlgorithmException("Provider IAIK not found!");
231            }
232            generator.initialize(bits);
233            KeyPair kp = generator.generateKeyPair();
234            return kp;
235      }
236      
237      /**
238       * Generates a RSASSA-PSS KeyPair.
239       * 
240       * @param int keyLength the key length
241       * @param hashAlgID the hash algorithm id (for the RSA-PSS params)
242       * @param saltLength the salt length to be used
243       * 
244       * @return the key pair 
245       */
246      private static KeyPair generateRSAPssKeyPair(int keyLength, 
247        AlgorithmID hashAlgID, int saltLength) throws NoSuchAlgorithmException {
248        KeyPair kp = null;
249    
250        
251          KeyPairGenerator keyGen = null;
252          try {
253            keyGen = KeyPairGenerator.getInstance("RSASSA-PSS", "IAIK");
254          } catch (NoSuchProviderException e) {
255            throw new NoSuchAlgorithmException(e.toString());
256          }
257    
258          // initialization with parameters for demonstration purposes (cast required)
259          RSAPssKeyPairGenerator rsaPsskeyGen = (RSAPssKeyPairGenerator) keyGen;
260    
261          RSAPssParameterSpec pssParamSpec = null;
262          if (hashAlgID != null) {
263            // create PSS parameters for specifying hash, mgf algorithms and salt length:
264            // hash and mgf algorithm ids
265            AlgorithmID hashID = (AlgorithmID) hashAlgID.clone();
266            AlgorithmID mgfID = (AlgorithmID) AlgorithmID.mgf1.clone();
267            mgfID.setParameter(hashID.toASN1Object());
268            // hash and mgf engines
269            MessageDigest hashEngine = hashID.getMessageDigestInstance();
270            MaskGenerationAlgorithm mgfEngine = mgfID.getMaskGenerationAlgorithmInstance();
271            MGF1ParameterSpec mgf1ParamSpec = new MGF1ParameterSpec(hashID);
272            mgf1ParamSpec.setHashEngine(hashEngine);
273            try {
274              mgfEngine.setParameters(mgf1ParamSpec);
275            } catch (InvalidAlgorithmParameterException e) {
276              throw new NoSuchAlgorithmException(e.toString());
277            }
278            // create the RSAPssParameterSpec
279            pssParamSpec = new RSAPssParameterSpec(hashID, mgfID,
280                saltLength);
281            // set engines
282            pssParamSpec.setHashEngine(hashEngine);
283            pssParamSpec.setMGFEngine(mgfEngine);
284          }   
285          // initialize key pair generator
286          if (pssParamSpec != null) {
287            rsaPsskeyGen.initialize(keyLength, pssParamSpec);
288          } else {
289            rsaPsskeyGen.initialize(keyLength);
290          }
291          kp = rsaPsskeyGen.generateKeyPair();
292       
293        return kp;
294      }
295      
296      /**
297       * Creates a certificate from the given values.
298       *
299       * @param subject the subject of the certificate
300       * @param publicKey the public key to include
301       * @param issuer the issuer of the certificate
302       * @param privateKey the private key for signing the certificate
303       * @param algorithm the signature algorithm to use
304       * @param keyID the key id for the AuthotityKeyIdentifier extension
305       * @param forSigning if the certificate to be created shall be used for signing or encryption
306       * @param tspServer whether to create a TSP server certificate
307       *
308       * @return the certificate just created
309       */
310      private static X509Certificate createCertificate(Name subject, PublicKey publicKey, 
311          Name issuer, PrivateKey privateKey, AlgorithmID algorithm, byte[] keyID, 
312          boolean forSigning, boolean tspServer) {
313    
314        // create a new certificate
315        X509Certificate cert = new X509Certificate();
316    
317        try {
318          // set the values
319          cert.setSerialNumber(new BigInteger(20, new Random()));
320          cert.setSubjectDN(subject);
321          cert.setPublicKey(publicKey);
322          cert.setIssuerDN(issuer);
323    
324          GregorianCalendar date = new GregorianCalendar();
325          // not before now
326          cert.setValidNotBefore(date.getTime());
327    
328          if (issuer.equals(subject)) {
329            // CA certificate
330            date.add(Calendar.YEAR, 10); 
331            BasicConstraints basicConstraints = new BasicConstraints(true);
332            cert.addExtension(basicConstraints);
333            KeyUsage keyUsage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign);
334            cert.addExtension(keyUsage);
335          } else { 
336            date.add(Calendar.YEAR, 9);
337            KeyUsage keyUsage = null;
338            if (forSigning) {
339              keyUsage = new KeyUsage(KeyUsage.digitalSignature |
340                                      KeyUsage.nonRepudiation);
341              if (tspServer) {
342                // certificate for time stamp server
343                ExtendedKeyUsage extKeyUsage = new ExtendedKeyUsage(ExtendedKeyUsage.timeStamping);
344                extKeyUsage.setCritical(true);
345                cert.addExtension(extKeyUsage);
346              }
347            } else {                  
348              if (publicKey.getAlgorithm().toUpperCase().endsWith("DH")) {
349                keyUsage = new KeyUsage(KeyUsage.keyAgreement) ; 
350              } else { 
351                keyUsage = new KeyUsage(KeyUsage.keyEncipherment |
352                                        KeyUsage.dataEncipherment);
353              }                          
354            }                          
355            cert.addExtension(keyUsage);
356            AuthorityKeyIdentifier authID = new AuthorityKeyIdentifier();
357            authID.setKeyIdentifier(keyID);
358            cert.addExtension(authID);
359            GeneralNames generalNames = new GeneralNames();
360            generalNames.addName(new GeneralName(GeneralName.rfc822Name, "smimetest@iaik.tugraz.at"));
361            SubjectAltName subjectAltName = new SubjectAltName(generalNames);
362            cert.addExtension(subjectAltName);
363          }
364          String explicitText = "This certificate may be used for testing purposes only";
365          PolicyQualifierInfo policyQualifier = new PolicyQualifierInfo(null, null, explicitText);
366          PolicyInformation[] policyInformations = 
367            { new PolicyInformation(new ObjectID("1.3.6.1.4.1.2706.2.2.4.1.1.1.1"),
368                                  new PolicyQualifierInfo[] { policyQualifier }) };
369          CertificatePolicies certPolicies = new CertificatePolicies(policyInformations);                        
370          
371          SubjectKeyIdentifier subjectKeyID = new SubjectKeyIdentifier(cert.getPublicKey());
372          cert.addExtension(subjectKeyID);
373            
374          cert.addExtension(certPolicies);                              
375          cert.setValidNotAfter(date.getTime());
376          // and sign the certificate
377          cert.sign(algorithm ,privateKey);
378        } catch (CertificateException ex) {
379          throw new RuntimeException("Error creating the certificate: "+ex.getMessage());
380        } catch (InvalidKeyException ex) {
381          throw new RuntimeException("Error creating the certificate: "+ex.getMessage());
382        } catch (NoSuchAlgorithmException ex) {
383          throw new RuntimeException("Error creating the certificate: "+ex.getMessage());
384        } catch (X509ExtensionException ex) {
385          throw new RuntimeException("Error adding extension: "+ex.getMessage());   
386        } catch (CodingException ex) {
387          throw new RuntimeException("Error adding SubjectKeyIdentifier extension: "+ex.getMessage());   
388        }     
389        return cert;
390      }
391    
392      /**
393       * Load or create a KeyStore and initialize it.
394       */
395      private void initializeKeyStore() {
396     
397        BufferedReader reader = null;
398        if (!DemoUtil.CREATE_DEMO_KEYSTORE_AUTOMATICAllY) {
399          reader = new BufferedReader(new InputStreamReader(System.in));
400        }
401        String line;
402    
403        try {
404          // default directory is the current user dir
405          String keystore_dir = System.getProperty("user.dir");
406          File ks = new File(keystore_dir, ks_filename);
407    
408          // KeyStore does already exist
409          if (ks.exists()) {
410            keystore_file = ks.getAbsolutePath();
411            if (create_only_certificates) {
412              System.out.println("Create only new certificates from already existing keys!");
413            }
414            else {
415              System.out.println("Existing KeyStore will be deleted!");
416            }
417            System.out.println("KeyStore: "+keystore_file);
418          }
419          else {
420            // there is no KeyStore -> create also new keys
421            create_only_certificates = false;
422            
423            if (!DemoUtil.CREATE_DEMO_KEYSTORE_AUTOMATICAllY) {
424              while (true) {
425                System.out.print("Create new KeyStore in directory: "+keystore_dir+" [y]");
426                line = readLine(reader);
427                if (line.length() == 0 || line.equals("y")) {
428                  ks = new File(keystore_dir, ks_filename);
429                  keystore_file = ks.getAbsolutePath();
430                  System.out.println("KeyStore will be saved to: "+keystore_file);
431                  break;
432                }
433                System.out.print("Enter directory: ");
434                keystore_dir = reader.readLine();
435              }
436            } else {
437              System.out.print("Create new KeyStore in directory: "+keystore_dir+" ...");
438              ks = new File(keystore_dir, ks_filename);
439              keystore_file = ks.getAbsolutePath();
440              System.out.println("KeyStore will be saved to: "+keystore_file);
441            }
442          }
443          
444          // get a new KeyStore object
445          key_store = SecurityProvider.getSecurityProvider().getKeyStore("IAIKKeyStore");
446          
447          if (create_only_certificates) {
448            // take private keys from existing KeyStore
449            FileInputStream fis = null;
450            try {
451              fis = new FileInputStream(ks); 
452              key_store.load(fis, KS_PASSWORD);
453            } finally {
454              if (fis != null) {
455                try {
456                  fis.close();
457                } catch (IOException ex) {
458                  // ignore
459                }
460              }
461            }
462          }
463          else {
464            // create a new KeyStore
465            key_store.load(null, null);
466          }
467          
468        } catch (Exception ex) {
469          System.out.println("Error creating new IAIK KeyStore!");
470          throw new RuntimeException("Error creating new KeyStore: "+ex.getMessage());
471        }
472      }
473    
474      /**
475       * Save the KeyStore to disk.
476       */
477      private void saveKeyStore() {
478        FileOutputStream os = null;
479        try {
480          // write the KeyStore to disk
481          os = new FileOutputStream(keystore_file);
482          key_store.store(os, KS_PASSWORD);
483    
484        } catch (Exception ex) {
485          System.out.println("Error saving KeyStore!");
486          ex.printStackTrace();
487        } finally {
488          if (os != null) {
489            try {
490              os.close();
491            } catch (IOException ex) {
492              // ignore
493            }
494          }
495        }
496      }
497    
498      /**
499       * Adds the private key and the certificate chain to the key store.
500       *
501       * @param keyPair the key pair with the private key to be added
502       * @param chain the certificate chain to be added
503       * @param alias the alias for the keystore entry
504       *
505       * @throws KeyStoreException if an error occurs when trying to add the key
506       */
507      public void addToKeyStore(KeyPair keyPair, X509Certificate[] chain, String alias) throws KeyStoreException {
508        key_store.setKeyEntry(alias, keyPair.getPrivate(), KS_PASSWORD, chain);
509      }
510      
511      /**
512       * Returns a KeyPair form the KeyStore.
513       *
514       * @return the KeyPair of the given type
515       *
516       * @throws Exception if some error occurs
517       */
518      private KeyPair getKeyPair(String type) throws Exception {
519        KeyPair kp = null;
520        PrivateKey privKey = (PrivateKey)key_store.getKey(type, KS_PASSWORD);
521        if (privKey != null) {
522          PublicKey pubKey = key_store.getCertificateChain(type)[0].getPublicKey();
523          kp = new KeyPair(pubKey, privKey);
524        }
525        return kp;
526      }
527    
528      /**
529       * Get all private keys from the KeyStore.
530       */
531      private void getPrivateKeys() {
532        // RSA    
533        try {
534          ca_rsa = getKeyPair(CA_RSA);
535          // for signing
536          rsa2048_sign_1 = getKeyPair(RSA_2048_SIGN_1);
537          rsa2048_sign_2 = getKeyPair(RSA_2048_SIGN_2);
538          rsa2048_sign_3 = getKeyPair(RSA_2048_SIGN_3);
539          // for encrypting
540          rsa2048_crypt_1 = getKeyPair(RSA_2048_CRYPT_1);
541          rsa2048_crypt_2 = getKeyPair(RSA_2048_CRYPT_2);
542          rsa2048_crypt_3 = getKeyPair(RSA_2048_CRYPT_3);
543        } catch (Exception ex) {
544          System.out.println("Unable to get RSA keys from KeyStore: " + ex.toString());
545          create_rsa = false;
546        }
547        // DSA
548        try {
549          ca_dsa = getKeyPair(CA_DSA);
550          dsa1024 = getKeyPair(DSA_1024);
551        } catch (Exception ex) {
552          System.out.println("Unable to get DSA keys from KeyStore: " + ex.toString());
553          create_dsa = false;
554        }
555        // DSA with SHA-2
556        try {
557          dsa2048 = getKeyPair(DSA_2048);
558          dsa3072 = getKeyPair(DSA_3072);
559        } catch (Exception ex) {
560          System.out.println("Unable to get DSA SHA-2 keys from KeyStore: " + ex.toString());
561          create_dsa_sha2 = false;
562        }
563        // ESDH
564        try {
565          esdh2048_1 = getKeyPair(ESDH_2048_1);
566          esdh2048_2 = getKeyPair(ESDH_2048_2);
567        } catch (Exception ex) {
568          System.out.println("Unable to get ESDH keys from KeyStore: " + ex.toString());
569          create_esdh = false;
570        }
571        // SSDH
572        try {
573          ssdh2048_1 = getKeyPair(SSDH_2048_1);
574          ssdh2048_2 = getKeyPair(SSDH_2048_2);
575        } catch (Exception ex) {
576          System.out.println("Unable to get SSDH keys from KeyStore: " + ex.toString());
577          create_ssdh = false;
578        }
579        // TSP server
580        try {
581          tsp_server = getKeyPair(TSP_SERVER);
582        } catch (Exception ex) {
583          System.out.println("Unable to get TSP server key from KeyStore: " + ex.toString());
584          create_tspserver = false;
585        }
586        
587        // RSA-PSS    
588        try {
589          ca_rsa_pss = getKeyPair(CA_RSAPSS);
590          // for signing
591          rsapss2048_sha1_sign = getKeyPair(RSAPSS_2048_SHA1_SIGN);
592          rsapss2048_sha256_sign = getKeyPair(RSAPSS_2048_SHA256_SIGN);
593          rsapss2048_sha384_sign = getKeyPair(RSAPSS_2048_SHA384_SIGN);
594          rsapss2048_sha512_sign = getKeyPair(RSAPSS_2048_SHA512_SIGN);
595        } catch (Exception ex) {
596          System.out.println("Unable to get RSA-PSS keys from KeyStore: " + ex.toString());
597          create_rsa_pss = false;
598        }
599        
600      }
601    
602      /**
603       * Generates new prviate keys.
604       */
605      private void generatePrivateKeys() {
606        try {
607              // first create the KeyPairs
608              if (create_rsa) {
609                try {
610              System.out.println("generate RSA KeyPair for CA certificate ["+CA_KEYLENGTH+" bits]...");
611                  ca_rsa = generateKeyPair("RSA", CA_KEYLENGTH);
612              System.out.println("Generate RSA signing keys...");
613              System.out.println("generate RSA KeyPair for a test certificate [2048 bits]...");
614              rsa2048_sign_1 = generateKeyPair("RSA", 2048);
615              System.out.println("generate second RSA KeyPair for a test certificate [2048 bits]...");
616              rsa2048_sign_2 = generateKeyPair("RSA", 2048);
617              System.out.println("generate third RSA KeyPair for a test certificate [2048 bits]...");
618              rsa2048_sign_3 = generateKeyPair("RSA", 2048);
619              System.out.println("Generate RSA encryption keys...");
620              System.out.println("generate RSA KeyPair for a test certificate [2048 bits]...");
621              rsa2048_crypt_1 = generateKeyPair("RSA", 2048); 
622              System.out.println("generate second RSA KeyPair for a test certificate [2048 bits]...");
623              rsa2048_crypt_2 = generateKeyPair("RSA", 2048); 
624              System.out.println("generate third RSA KeyPair for a test certificate [2048 bits]...");
625              rsa2048_crypt_3 = generateKeyPair("RSA", 2048); 
626              
627                } catch (NoSuchAlgorithmException ex) {
628              create_rsa = false;
629              System.out.println("No implementation for RSA! RSA certificates are not created!\n");
630                }
631              }
632              
633          if (create_rsa_pss) {
634            try {
635              System.out.println("generate RSA-PSS KeyPair for CA certificate 2048 bits]...");
636              ca_rsa_pss = generateRSAPssKeyPair(2048, AlgorithmID.sha256, 32);
637              System.out.println("Generate RSA-PSS signing keys...");
638              System.out.println("generate RSA-PSS KeyPair for a test certificate [2048 bits, SHA-1]...");
639              rsapss2048_sha1_sign = generateRSAPssKeyPair(2048, AlgorithmID.sha1, 32);
640              System.out.println("generate RSA-PSS KeyPair for a test certificate [2048 bits, SHA-256]...");
641              rsapss2048_sha256_sign = generateRSAPssKeyPair(2048, AlgorithmID.sha256, 32);
642              System.out.println("generate RSA-PSS KeyPair for a test certificate [2048 bits, SHA-384]...");
643              rsapss2048_sha384_sign = generateRSAPssKeyPair(2048, AlgorithmID.sha384, 48);
644              System.out.println("generate RSA-PSS KeyPair for a test certificate [2048 bits, SHA-512]...");
645              rsapss2048_sha512_sign = generateRSAPssKeyPair(2048,  AlgorithmID.sha512, 64);
646              
647            } catch (NoSuchAlgorithmException ex) {
648              create_rsa_pss = false;
649              System.out.println("No implementation for RSA! RSA certificates are not created!\n");
650            }
651          }
652          
653          if (create_dsa) {
654                try {
655              System.out.println("generate DSA KeyPair for CA certificate [3072 bits]...");
656                  ca_dsa = generateKeyPair("SHA256withDSA", 3072);
657                  System.out.println("generate DSA KeyPair for a test certificate [1024 bits]...");
658              dsa1024 = generateKeyPair("DSA", 1024);
659                } catch (NoSuchAlgorithmException ex) {
660              create_dsa = false;
661              System.out.println("No implementation for DSA! DSA certificates are not created!\n");
662                }
663          }
664          
665          if (create_dsa_sha2) {
666            try {
667              System.out.println("generate DSA SHA-224 KeyPair for a test certificate [2048 bits]...");
668              dsa2048 = generateKeyPair("SHA224withDSA", 2048);
669              System.out.println("generate DSA SHA-256 KeyPair for a test certificate [3072 bits]...");
670              dsa3072 = generateKeyPair("SHA256withDSA", 3072);
671            } catch (NoSuchAlgorithmException ex) {
672              create_dsa = false;
673              System.out.println("No implementation for SHA2-DSA! SHA2-DSA certificates are not created!\n");
674            }
675          }
676          
677          if (create_esdh) {
678            try {
679              System.out.println("generate ESDH KeyPair for a test certificate [2048 bits]...");
680              esdh2048_1 = generateKeyPair("ESDH", 2048);
681              System.out.println("generate second ESDH KeyPair for a test certificate [2048 bits]...");
682              esdh2048_2 = generateKeyPair("ESDH", 2048);
683                } catch (NoSuchAlgorithmException ex) {
684              create_esdh = false;
685              System.out.println("No implementation for ESDH! ESDH certificates are not created!\n");
686                }
687              }  
688              
689              if (create_ssdh) {
690            try {
691              System.out.println("generate SSDH KeyPair for a test certificate [2048 bits]...");
692              // key alg id the same as ESDH
693              ssdh2048_1 = generateKeyPair("ESDH", 2048);
694              System.out.println("generate second SSDH KeyPair for a test certificate [2048 bits]...");
695              ssdh2048_2 = generateKeyPair("ESDH", 2048);
696            } catch (NoSuchAlgorithmException ex) {
697              create_ssdh = false;
698              System.out.println("No implementation for SSDH! SSDH certificates are not created!\n");
699                }
700              }
701          
702          if (create_tspserver) {
703            try {
704              System.out.println("generate RSA KeyPair for a tsp server test certificate [2048 bits]...");
705              tsp_server = generateKeyPair("RSA", 2048);
706            } catch (NoSuchAlgorithmException ex) {
707              create_tspserver = false;
708              System.out.println("No implementation for RSA! TSP server certificate not created!\n");
709            }
710          }
711          
712                      
713        } catch (Exception ex) {
714          System.out.println("Exception: "+ex);
715        }
716      }
717      
718      /**
719       * Generates the certificates.
720       */
721      public void generateCertificates() {
722    
723        try {
724    
725          // Now create the certificates
726          Name issuer = new Name();
727          issuer.addRDN(ObjectID.country, "AT");
728          issuer.addRDN(ObjectID.organization ,"IAIK");
729          issuer.addRDN(ObjectID.organizationalUnit ,"JavaSecurity");
730    
731          Name subject = new Name();
732          subject.addRDN(ObjectID.country, "AT");
733          subject.addRDN(ObjectID.organization ,"IAIK");
734          subject.addRDN(ObjectID.organizationalUnit ,"JavaSecurity");
735          
736          AlgorithmID rsaPssSigningAlg = DemoUtil.createPssAlgorithmID(AlgorithmID.sha256, AlgorithmID.mgf1, 32);
737    
738          //
739          // create self signed CA certs
740          //
741          X509Certificate caRSA = null;
742          X509Certificate caRSAPSS = null;
743          X509Certificate caDSA = null;
744          X509Certificate[] chain = new X509Certificate[1];
745          // for verifying the created certificates
746          SimpleChainVerifier verifier = new SimpleChainVerifier();
747    
748          if (create_rsa) {
749            issuer.addRDN(ObjectID.commonName ,"IAIK RSA Test CA");
750            System.out.println("create self signed RSA CA certificate...");
751            caRSA = createCertificate(issuer, 
752                                      ca_rsa.getPublic(),
753                                      issuer,
754                                      ca_rsa.getPrivate(),
755                                      (AlgorithmID)AlgorithmID.sha256WithRSAEncryption.clone(),
756                                      null,
757                                      true,
758                                      false);
759            // verify the self signed certificate
760            caRSA.verify();
761            // set the CA cert as trusted root
762            verifier.addTrustedCertificate(caRSA);
763            chain[0] = caRSA;
764            addToKeyStore(ca_rsa, chain, CA_RSA);
765            issuer.removeRDN(ObjectID.commonName);
766          }
767          
768          if (create_rsa_pss) {
769            issuer.addRDN(ObjectID.commonName ,"IAIK RSA-PSS Test CA");
770            System.out.println("create self signed RSA-PSS CA certificate...");
771            caRSAPSS = createCertificate(issuer, 
772                                      ca_rsa_pss.getPublic(),
773                                      issuer,
774                                      ca_rsa_pss.getPrivate(),
775                                      (AlgorithmID)rsaPssSigningAlg.clone(),
776                                      null,
777                                      true,
778                                      false);
779            // verify the self signed certificate
780            caRSAPSS.verify();
781            // set the CA cert as trusted root
782            verifier.addTrustedCertificate(caRSAPSS);
783            chain[0] = caRSAPSS;
784            addToKeyStore(ca_rsa_pss, chain, CA_RSAPSS);
785            issuer.removeRDN(ObjectID.commonName);
786          }
787    
788          if (create_dsa) {
789            issuer.addRDN(ObjectID.commonName ,"IAIK DSA Test CA");
790            System.out.println("create self signed DSA CA certificate...");
791            caDSA = createCertificate(issuer, 
792                                      ca_dsa.getPublic(),
793                                      issuer,
794                                      ca_dsa.getPrivate(),
795                                      (AlgorithmID)AlgorithmID.dsaWithSHA256.clone(),
796                                      null,
797                                      true,
798                                      false);
799            // verify the self signed certificate
800            caDSA.verify();
801            // set the CA cert as trusted root
802            verifier.addTrustedCertificate(caDSA);
803            chain[0] = caDSA;
804            addToKeyStore(ca_dsa, chain, CA_DSA);
805            issuer.removeRDN(ObjectID.commonName);
806          }
807    
808          //
809          // create certificates
810          //
811          chain = new X509Certificate[2];
812                
813          // create a RSA certificate
814          if (create_rsa) {
815            issuer.addRDN(ObjectID.commonName ,"IAIK RSA Test CA");
816            SubjectKeyIdentifier subjectKeyID = (SubjectKeyIdentifier)caRSA.getExtension(SubjectKeyIdentifier.oid);
817            subject.removeRDN(ObjectID.commonName);
818            
819            // 2048
820            subject.addRDN(ObjectID.commonName ,"RSA 2048 bit Demo Signing Certificate 1");
821            System.out.println("create 2048 bit RSA demo certificate...");
822            chain[0] = createCertificate(subject,
823                                         rsa2048_sign_1.getPublic(),
824                                         issuer, 
825                                         ca_rsa.getPrivate(),
826                                         (AlgorithmID)AlgorithmID.sha256WithRSAEncryption.clone(),
827                                         subjectKeyID.get(),
828                                         true,
829                                         false);
830            chain[1] = caRSA;
831            verifier.verifyChain(chain);
832           
833            addToKeyStore(rsa2048_sign_1, chain, RSA_2048_SIGN_1);
834            subject.removeRDN(ObjectID.commonName);
835            
836            subject.addRDN(ObjectID.commonName ,"RSA 2048 bit Demo Signing Certificate 2");
837            System.out.println("create second 2048 bit RSA demo certificate...");
838            chain[0] = createCertificate(subject,
839                                         rsa2048_sign_2.getPublic(),
840                                         issuer, 
841                                         ca_rsa.getPrivate(),
842                                         (AlgorithmID)AlgorithmID.sha256WithRSAEncryption.clone(),
843                                         subjectKeyID.get(),
844                                         true,
845                                         false);
846            chain[1] = caRSA;
847            verifier.verifyChain(chain);
848           
849            addToKeyStore(rsa2048_sign_2, chain, RSA_2048_SIGN_2);
850            subject.removeRDN(ObjectID.commonName);
851            
852            subject.addRDN(ObjectID.commonName ,"RSA 2048 bit Demo Signing Certificate 3");
853            System.out.println("create third 2048 bit RSA demo certificate...");
854            chain[0] = createCertificate(subject,
855                                         rsa2048_sign_3.getPublic(),
856                                         issuer, 
857                                         ca_rsa.getPrivate(),
858                                         (AlgorithmID)AlgorithmID.sha256WithRSAEncryption.clone(),
859                                         subjectKeyID.get(),
860                                         true,
861                                         false);
862            chain[1] = caRSA;
863            verifier.verifyChain(chain);
864           
865            addToKeyStore(rsa2048_sign_3, chain, RSA_2048_SIGN_3);
866            subject.removeRDN(ObjectID.commonName);
867          
868            // for encrypting
869            System.out.println("Create RSA demo certificates to be used for encryption...");
870     
871            // 2048
872           
873            subject.addRDN(ObjectID.commonName ,"RSA 2048 bit Demo Encryption Certificate 1");
874            System.out.println("create 2048 bit RSA demo encryption certificate...");
875            chain[0] = createCertificate(subject, 
876                                         rsa2048_crypt_1.getPublic(),
877                                         issuer,
878                                         ca_rsa.getPrivate(),
879                                         (AlgorithmID)AlgorithmID.sha256WithRSAEncryption.clone(),
880                                         subjectKeyID.get(),
881                                         false,
882                                         false);
883            chain[1] = caRSA;
884            verifier.verifyChain(chain);
885            addToKeyStore(rsa2048_crypt_1, chain, RSA_2048_CRYPT_1);
886            subject.removeRDN(ObjectID.commonName); 
887            
888            subject.addRDN(ObjectID.commonName ,"RSA 2048 bit Demo Encryption Certificate 2");
889            System.out.println("create second 2048 bit RSA demo encryption certificate...");
890            chain[0] = createCertificate(subject, 
891                                         rsa2048_crypt_2.getPublic(),
892                                         issuer,
893                                         ca_rsa.getPrivate(),
894                                         (AlgorithmID)AlgorithmID.sha256WithRSAEncryption.clone(),
895                                         subjectKeyID.get(),
896                                         false,
897                                         false);
898            chain[1] = caRSA;
899            verifier.verifyChain(chain);
900            addToKeyStore(rsa2048_crypt_2, chain, RSA_2048_CRYPT_2);
901            subject.removeRDN(ObjectID.commonName);  
902            
903            subject.addRDN(ObjectID.commonName ,"RSA 2048 bit Demo Encryption Certificate 3");
904            System.out.println("create third 2048 bit RSA demo encryption certificate...");
905            chain[0] = createCertificate(subject, 
906                                         rsa2048_crypt_3.getPublic(),
907                                         issuer,
908                                         ca_rsa.getPrivate(),
909                                         (AlgorithmID)AlgorithmID.sha256WithRSAEncryption.clone(),
910                                         subjectKeyID.get(),
911                                         false,
912                                         false);
913            chain[1] = caRSA;
914            verifier.verifyChain(chain);
915            addToKeyStore(rsa2048_crypt_3, chain, RSA_2048_CRYPT_3);
916            subject.removeRDN(ObjectID.commonName);  
917            issuer.removeRDN(ObjectID.commonName);
918          }
919          
920          // create a RSA-PSS certificate
921          if (create_rsa_pss) {
922            issuer.addRDN(ObjectID.commonName ,"IAIK RSA-PSS Test CA");
923            SubjectKeyIdentifier subjectKeyID = (SubjectKeyIdentifier)caRSAPSS.getExtension(SubjectKeyIdentifier.oid);
924           
925           
926            // 2048
927          
928            // SHA-1
929            subject.addRDN(ObjectID.commonName ,"RSA-PSS 2048 bit SHA-1 Demo Signing Certificate");
930            System.out.println("create 2048 bit RSA-PSS (SHA-1) demo certificate...");
931            chain[0] = createCertificate(subject,
932                                         rsapss2048_sha1_sign.getPublic(),
933                                         issuer, 
934                                         ca_rsa_pss.getPrivate(),
935                                         (AlgorithmID)rsaPssSigningAlg.clone(),
936                                         subjectKeyID.get(),
937                                         true,
938                                         false);
939            chain[1] = caRSAPSS;
940            verifier.verifyChain(chain);
941           
942            addToKeyStore(rsapss2048_sha1_sign, chain, RSAPSS_2048_SHA1_SIGN);
943            subject.removeRDN(ObjectID.commonName);
944            
945            // SHA-256
946            subject.addRDN(ObjectID.commonName ,"RSA-PSS 2048 bit SHA-256 Demo Signing Certificate");
947            System.out.println("create 2048 bit RSA-PSS (SHA-256) demo certificate...");
948            chain[0] = createCertificate(subject,
949                                         rsapss2048_sha256_sign.getPublic(),
950                                         issuer, 
951                                         ca_rsa_pss.getPrivate(),
952                                         (AlgorithmID)rsaPssSigningAlg.clone(),
953                                         subjectKeyID.get(),
954                                         true,
955                                         false);
956            chain[1] = caRSAPSS;
957            verifier.verifyChain(chain);
958           
959            addToKeyStore(rsapss2048_sha256_sign, chain, RSAPSS_2048_SHA256_SIGN);
960            subject.removeRDN(ObjectID.commonName);
961            
962            // SHA-384
963            subject.addRDN(ObjectID.commonName ,"RSA-PSS 2048 bit SHA-384 Demo Signing Certificate");
964            System.out.println("create 2048 bit RSA-PSS (SHA-384) demo certificate...");
965            chain[0] = createCertificate(subject,
966                                         rsapss2048_sha384_sign.getPublic(),
967                                         issuer, 
968                                         ca_rsa_pss.getPrivate(),
969                                         (AlgorithmID)rsaPssSigningAlg.clone(),
970                                         subjectKeyID.get(),
971                                         true,
972                                         false);
973            chain[1] = caRSAPSS;
974            verifier.verifyChain(chain);
975           
976            addToKeyStore(rsapss2048_sha384_sign, chain, RSAPSS_2048_SHA384_SIGN);
977            subject.removeRDN(ObjectID.commonName);
978            
979            // SHA-512
980            subject.addRDN(ObjectID.commonName ,"RSA-PSS 2048 bit SHA-512 Demo Signing Certificate");
981            System.out.println("create 2048 bit RSA-PSS (SHA-512) demo certificate...");
982            chain[0] = createCertificate(subject,
983                                         rsapss2048_sha512_sign.getPublic(),
984                                         issuer, 
985                                         ca_rsa_pss.getPrivate(),
986                                         (AlgorithmID)rsaPssSigningAlg.clone(),
987                                         subjectKeyID.get(),
988                                         true,
989                                         false);
990            chain[1] = caRSAPSS;
991            verifier.verifyChain(chain);
992           
993            addToKeyStore(rsapss2048_sha512_sign, chain, RSAPSS_2048_SHA512_SIGN);
994            subject.removeRDN(ObjectID.commonName);
995          
996           
997          }
998          
999          // create a DSA test certificate
1000          if (create_dsa) {
1001            issuer.addRDN(ObjectID.commonName ,"IAIK DSA Test CA");
1002            SubjectKeyIdentifier subjectKeyID = (SubjectKeyIdentifier)caDSA.getExtension(SubjectKeyIdentifier.oid);
1003            
1004            // 1024
1005            subject.addRDN(ObjectID.commonName ,"DSA 1024 bit Demo Certificate");
1006            System.out.println("create 1024 bit DSA demo certificate...");
1007            chain[0] = createCertificate(subject, 
1008                                         dsa1024.getPublic(),
1009                                         issuer, 
1010                                         ca_dsa.getPrivate(),
1011                                         (AlgorithmID)AlgorithmID.dsaWithSHA256.clone(),
1012                                         subjectKeyID.get(),
1013                                         true,
1014                                         false);
1015            subject.removeRDN(ObjectID.commonName);
1016            chain[1] = caDSA;
1017            verifier.verifyChain(chain);
1018            addToKeyStore(dsa1024, chain, DSA_1024);
1019            issuer.removeRDN(ObjectID.commonName);
1020          }
1021          
1022          // create SHA-2 DSA test certificates
1023          if (create_dsa_sha2) {
1024            issuer.addRDN(ObjectID.commonName ,"IAIK DSA Test CA");
1025            // 2048
1026            subject.addRDN(ObjectID.commonName ,"DSA SHA-224 2048 bit Test Certificate");
1027            System.out.println("create 2048 bit SHA224withDSA test certificate...");
1028            SubjectKeyIdentifier subjectKeyID = (SubjectKeyIdentifier)caDSA.getExtension(SubjectKeyIdentifier.oid);
1029            chain[0] = createCertificate(subject, dsa2048.getPublic(),
1030                  issuer, ca_dsa.getPrivate(), AlgorithmID.dsaWithSHA256, subjectKeyID.get(), true, false);
1031            subject.removeRDN(ObjectID.commonName);
1032            chain[1] = caDSA;
1033            verifier.verifyChain(chain);
1034            addToKeyStore(dsa2048, chain, DSA_2048);
1035            
1036            // 3072
1037            subject.addRDN(ObjectID.commonName ,"DSA SHA-256 3072 bit Test Certificate");
1038            System.out.println("create 3072 bit SHA256withDSA test certificate...");
1039            chain[0] = createCertificate(subject, dsa3072.getPublic(),
1040                  issuer, ca_dsa.getPrivate(), AlgorithmID.dsaWithSHA256, subjectKeyID.get(), true, false);
1041            subject.removeRDN(ObjectID.commonName);
1042            chain[1] = caDSA;
1043            verifier.verifyChain(chain);
1044            addToKeyStore(dsa3072, chain, DSA_3072);
1045            issuer.removeRDN(ObjectID.commonName);
1046          }
1047          
1048          
1049          // create a ESDH test certificate
1050          if (create_esdh) {
1051            issuer.addRDN(ObjectID.commonName ,"IAIK RSA Test CA");
1052            SubjectKeyIdentifier subjectKeyID = (SubjectKeyIdentifier)caRSA.getExtension(SubjectKeyIdentifier.oid);
1053          
1054            // 2048
1055            subject.addRDN(ObjectID.commonName ,"ESDH 2048 bit Demo Certificate 1");
1056            System.out.println("create 2048 bit ESDH demo certificate...");
1057            chain[0] = createCertificate(subject,
1058                                         esdh2048_1.getPublic(),
1059                                         issuer,
1060                                         ca_rsa.getPrivate(), 
1061                                         (AlgorithmID)AlgorithmID.sha256WithRSAEncryption.clone(),
1062                                         subjectKeyID.get(),
1063                                         false,
1064                                         false);
1065            subject.removeRDN(ObjectID.commonName);
1066            chain[1] = caRSA;
1067            verifier.verifyChain(chain);
1068            addToKeyStore(esdh2048_1, chain, ESDH_2048_1);
1069            
1070            subject.addRDN(ObjectID.commonName ,"ESDH 2048 bit Demo Certificate 2");
1071            System.out.println("create second 2048 bit ESDH demo certificate...");
1072            chain[0] = createCertificate(subject,
1073                                         esdh2048_2.getPublic(),
1074                                         issuer,
1075                                         ca_rsa.getPrivate(), 
1076                                         (AlgorithmID)AlgorithmID.sha256WithRSAEncryption.clone(),
1077                                         subjectKeyID.get(),
1078                                         false,
1079                                         false);
1080            subject.removeRDN(ObjectID.commonName);
1081            chain[1] = caRSA;
1082            verifier.verifyChain(chain);
1083            addToKeyStore(esdh2048_2, chain, ESDH_2048_2);
1084            
1085            issuer.removeRDN(ObjectID.commonName);
1086          }
1087          
1088              // create a SSDH test certificate
1089          if (create_ssdh) {
1090            issuer.addRDN(ObjectID.commonName ,"IAIK RSA Test CA");
1091            SubjectKeyIdentifier subjectKeyID = (SubjectKeyIdentifier)caRSA.getExtension(SubjectKeyIdentifier.oid);
1092            // 2048
1093            subject.addRDN(ObjectID.commonName ,"SSDH 2048 bit Demo Certificate 1");
1094            System.out.println("create 2048 bit SSDH demo certificate...");
1095            chain[0] = createCertificate(subject,
1096                                         ssdh2048_1.getPublic(),
1097                                         issuer, 
1098                                         ca_rsa.getPrivate(), 
1099                                         (AlgorithmID)AlgorithmID.sha256WithRSAEncryption.clone(),
1100                                         subjectKeyID.get(),
1101                                         false,
1102                                         false);
1103            subject.removeRDN(ObjectID.commonName);
1104            chain[1] = caRSA;
1105            verifier.verifyChain(chain);
1106            addToKeyStore(ssdh2048_1, chain, SSDH_2048_1);
1107         
1108            subject.addRDN(ObjectID.commonName ,"SSDH 2048 bit Demo Certificate 2");
1109            System.out.println("create second 2048 bit SSDH demo certificate...");
1110            chain[0] = createCertificate(subject,
1111                                         ssdh2048_2.getPublic(),
1112                                         issuer, 
1113                                         ca_rsa.getPrivate(),
1114                                         (AlgorithmID)AlgorithmID.sha256WithRSAEncryption.clone(),
1115                                         subjectKeyID.get(),
1116                                         false, 
1117                                         false);
1118            subject.removeRDN(ObjectID.commonName);
1119            chain[1] = caRSA;
1120            verifier.verifyChain(chain);
1121            addToKeyStore(ssdh2048_2, chain, SSDH_2048_2);
1122            issuer.removeRDN(ObjectID.commonName);
1123          }
1124          
1125          if (create_tspserver) {
1126            issuer.addRDN(ObjectID.commonName ,"IAIK RSA Test CA");
1127            SubjectKeyIdentifier subjectKeyID = (SubjectKeyIdentifier)caRSA.getExtension(SubjectKeyIdentifier.oid);
1128            subject.addRDN(ObjectID.commonName ,"IAIK TSP Demo Server Certificate");
1129            System.out.println("create 2048 bit RSA TSP demo server certificate...");
1130            chain[0] = createCertificate(subject,
1131                                         tsp_server.getPublic(),
1132                                         issuer,
1133                                         ca_rsa.getPrivate(),
1134                                         (AlgorithmID)AlgorithmID.sha256WithRSAEncryption.clone(),
1135                                         subjectKeyID.get(),
1136                                         true,
1137                                         true);
1138            chain[1] = caRSA;
1139            verifier.verifyChain(chain);
1140            addToKeyStore(tsp_server, chain, TSP_SERVER);
1141            subject.removeRDN(ObjectID.commonName);
1142          
1143          }
1144          
1145               System.out.println("\nCertificates created!");
1146     
1147        } catch (Exception ex) {
1148          System.out.println("Exception: "+ex);
1149        }
1150      }
1151      
1152      /**
1153       * Starts the keystore setup.
1154       */
1155      public static void start() {
1156            SetupCMSKeyStore suks = new SetupCMSKeyStore();
1157        suks.initializeKeyStore();
1158        if (suks.create_only_certificates) {
1159            suks.getPrivateKeys();
1160        }
1161        else {
1162              suks.generatePrivateKeys();
1163            }
1164            suks.generateCertificates();
1165        suks.saveKeyStore();
1166      }
1167      
1168      /**
1169       * Reads the next line from the given BufferedReader.
1170       * 
1171       * @param reader the reader from which to read the line
1172       * 
1173       * @return the line just read
1174       * 
1175       * @throws IOException if an I/O error occurs
1176       */
1177      private final static String readLine(BufferedReader reader) throws IOException {
1178        String line = reader.readLine();
1179        if (line != null) {
1180          line = line.trim();
1181        } else {
1182          line = "";
1183        }
1184        return line;
1185      }
1186      
1187      /**
1188       * Creates the test certificates.
1189       */
1190      public static void main(String arg[]) throws IOException {
1191    
1192            DemoUtil.initDemos();
1193        start();    
1194    //    if (!DemoUtil.CREATE_DEMO_KEYSTORE_AUTOMATICAllY) {
1195    //      System.in.read();
1196    //    }  
1197      }
1198    }