Clover Coverage Report
Coverage timestamp: Sun Mar 23 2008 08:24:39 GMT
456   1,415   99   13.82
128   798   0.29   33
33     3.97  
1    
 
 
  TCBKeystoreManagement       Line # 91 456 99 51.1% 0.5105348
 
No Tests
 
1    /*
2    * Copyright (c) 2006, University of Kent
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions are met:
7    *
8    * Redistributions of source code must retain the above copyright notice, this
9    * list of conditions and the following disclaimer.
10    *
11    * Redistributions in binary form must reproduce the above copyright notice,
12    * this list of conditions and the following disclaimer in the documentation
13    * and/or other materials provided with the distribution.
14    *
15    * 1. Neither the name of the University of Kent nor the names of its
16    * contributors may be used to endorse or promote products derived from this
17    * software without specific prior written permission.
18    *
19    * 2. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
20    * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
21    * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22    * PURPOSE ARE DISCLAIMED.
23    *
24    * 3. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
25    * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26    * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27    * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28    * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29    * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31    * POSSIBILITY OF SUCH DAMAGE.
32    *
33    * 4. YOU AGREE THAT THE EXCLUSIONS IN PARAGRAPHS 2 AND 3 ABOVE ARE REASONABLE
34    * IN THE CIRCUMSTANCES. IN PARTICULAR, YOU ACKNOWLEDGE (1) THAT THIS
35    * SOFTWARE HAS BEEN MADE AVAILABLE TO YOU FREE OF CHARGE, (2) THAT THIS
36    * SOFTWARE IS NOT "PRODUCT" QUALITY, BUT HAS BEEN PRODUCED BY A RESEARCH
37    * GROUP WHO DESIRE TO MAKE THIS SOFTWARE FREELY AVAILABLE TO PEOPLE WHO WISH
38    * TO USE IT, AND (3) THAT BECAUSE THIS SOFTWARE IS NOT OF "PRODUCT" QUALITY
39    * IT IS INEVITABLE THAT THERE WILL BE BUGS AND ERRORS, AND POSSIBLY MORE
40    * SERIOUS FAULTS, IN THIS SOFTWARE.
41    *
42    * 5. This license is governed, except to the extent that local laws
43    * necessarily apply, by the laws of England and Wales.
44    */
45   
46    package issrg.SAWS;
47   
48    import issrg.SAWS.callback.CertificateDataCallback;
49    import issrg.SAWS.callback.SAWSChoiceCallback;
50    import issrg.SAWS.callback.SAWSGUICallbackHandler;
51    import issrg.SAWS.callback.SAWSPasswordCallback;
52    import issrg.SAWS.callback.SAWSTextInputCallback;
53    import issrg.SAWS.callback.SAWSTextOutputCallback;
54    import issrg.SAWS.util.CertificateData;
55    import issrg.SAWS.util.SAWSLogWriter;
56   
57    import java.util.*;
58    import java.io.*;
59   
60    import java.math.BigInteger;
61   
62    import java.security.*;
63    import javax.crypto.*;
64    import javax.crypto.spec.* ;
65   
66    import java.security.cert.Certificate;
67   
68    import java.security.cert.CertificateEncodingException;
69    import java.security.cert.CertificateException;
70    import java.security.cert.CertificateFactory;
71    import java.security.cert.X509Certificate;
72   
73    import javax.security.auth.callback.Callback;
74   
75    import javax.security.auth.callback.CallbackHandler;
76    import javax.security.auth.x500.X500Principal;
77   
78    import javax.security.auth.x500.X500PrivateCredential;
79   
80    import org.bouncycastle.asn1.x509.X509Name;
81    import org.bouncycastle.jce.PKCS10CertificationRequest;
82    import org.bouncycastle.jce.provider.BouncyCastleProvider;
83    import org.bouncycastle.x509.X509V1CertificateGenerator;
84   
85   
86    /**
87    * Class to manage the key store.
88    *
89    * @author W.Xu, E. Silva
90    */
 
91    public class TCBKeystoreManagement {
92   
93    private String encryptionKeystoreLocation = null;
94    private String signingKeystoreLocation = null;
95    private int numberOfPasswordShares = 2;
96    private int numberOfEncPasswordShares =2;
97    private String rootCA = null;
98    private String vtPKC = null;
99   
100    private File encryptionKeyfile = null;
101    private File signingKeyfile =null;
102    private String sawsPW =null;
103    private String sawsEncPW = null;
104   
105    // keys used in SAWS
106    private PublicKey sawsEncryptionPublicKey = null;
107    private PrivateKey sawsEncryptionPrivateKey = null;
108    private PublicKey sawsSigningPublicKey = null;
109    private PrivateKey sawsSigningPrivateKey = null;
110    private PublicKey vtEncryptionPublicKey = null;
111    private PublicKey rootCAPublicKey = null;
112    private int debugLevel = 0;
113   
114    private SecretKey sawsTCBSecretKey = null; // symmetric encryption key used to read and write lastSN and lastHash file
115    private PBEParameterSpec paramSpec = null;
116   
117    private byte[] baSigningPublicKeyCert = null;
118    private String signingAlgName = null;
119   
120    private CallbackHandler callbackHandler = new SAWSGUICallbackHandler();
121    private Callback[] cbs = null;
122    private byte hashAlgorithm = SAWSConstant.SHA1;
123   
124    private java.security.cert.Certificate sawsEncCertificate;
125    private java.security.cert.Certificate sawsSigCertificate;
126   
127    //adding log4j logging
128   
129    private static SAWSLogWriter sawsDebugLog = new SAWSLogWriter(TCBKeystoreManagement.class.getName());
130   
131   
132    /** Creates a new instance of TCBKeystoreManagement. */
133   
 
134  8 toggle public TCBKeystoreManagement(String signkeystoreLocation, int numOfPassShares,
135    String encKeystoreLocation, int numOfEncPassShares, String rootCAPara, String vtPKCPara,
136    int debugLevel) {
137  8 signingKeystoreLocation = signkeystoreLocation;
138  8 numberOfPasswordShares = numOfPassShares;
139  8 encryptionKeystoreLocation = encKeystoreLocation;
140  8 numberOfEncPasswordShares = numOfEncPassShares;
141  8 rootCA = rootCAPara;
142  8 vtPKC = vtPKCPara;
143  8 this.debugLevel = debugLevel;
144    }
145   
 
146  8 toggle public TCBKeystoreManagement(String signkeystoreLocation, int numOfPassShares,
147    String encKeystoreLocation, int numOfEncPassShares, String rootCAPara, String vtPKCPara,
148    int debugLevel, byte hashAlgorithm, CallbackHandler ch) {
149  8 this(signkeystoreLocation, numOfPassShares,
150    encKeystoreLocation, numOfEncPassShares, rootCAPara, vtPKCPara,
151    debugLevel);
152  8 this.hashAlgorithm = hashAlgorithm;
153  8 this.callbackHandler = ch;
154    }
155   
156    /**
157    * Checks if the signing keystore exists.
158    * SAWS stops if this keystore is missing.
159    */
 
160  5 toggle public void checkSigningKeystoreFile() {
161  5 signingKeyfile = new File( signingKeystoreLocation );
162  5 if ( !signingKeyfile.exists() ) {
163  0 this.showMessage("The signing keystore is missing: " + signingKeystoreLocation
164    + "\n\nThis is the first time to run SAWS, or the signing keystore has been removed illegally."
165    + "\nSAWS will stop. Please use SAWS to generate a new signing keystore, then restart SAWS.",
166    SAWSTextOutputCallback.WARNING);
167  0 System.exit(-1);
168    }
169    }
170    /**
171    * Checks if the encryption keystore exists.
172    * SAWS stops if this keystore is missing.
173    */
 
174  4 toggle public void checkEncKeystoreFile(){
175  4 encryptionKeyfile = new File( encryptionKeystoreLocation );
176  4 if ( !encryptionKeyfile.exists() ) {
177  0 this.showMessage("The encryption keystore is missing: " + encryptionKeystoreLocation
178    + "\n\nThis is the first time to run SAWS, or the encryption keystore is removed illegally. "
179    + "\nSAWS will stop. "
180    + "\nPlease recover the encryption keystore from your backup if you have backed it up before, "
181    + "\nor use SAWS to create a new encryption keystore, then restart SAWS.",
182    SAWSTextOutputCallback.WARNING);
183   
184    /*Object[] options = { "Stop" };
185    int selectRootCA = JOptionPane.showOptionDialog(null,
186    "The encryption keystore is missing: " + encryptionKeystoreLocation +
187    "\n\nThis is the first time to run SAWS, or the encryption keystore is removed illegally. " +
188    "\n SAWS will stop. " +
189    "\nPlease recover the encryption keystore from your backup if you have backed it up before, " +
190    "\nor use SAWS to create a new encryption keystore," +
191    " then restart SAWS.",
192    "Warning",
193    JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
194    null, options, options[0]);*/
195  0 System.exit(-1);
196    }
197   
198    }
199   
200    /**
201    * This method reads in the signing keypair and the encryption keypair, generates the symmetric key used for reading
202    * and writing lastSN and lastHash files. Called by SAWSServer().
203    *
204    */
 
205  4 toggle public void readKeystores(){
206    //System.out.println("Now please input the password for the signing keystore in the pop-up window:");
207  4 sawsPW = getSAWSPassword3Attempts(signingKeystoreLocation, numberOfPasswordShares, "signing", false);
208  4 if (sawsPW == null ) {
209  0 System.exit(-1);
210    }
211    //System.out.println("Now please input the password for the encryption keystore in the pop-up window:");
212  4 sawsEncPW = getSAWSPassword3Attempts(encryptionKeystoreLocation, numberOfEncPasswordShares, "encryption", false);
213  4 if (sawsEncPW == null ) {
214  0 System.exit(-1);
215    }
216   
217    // read saws signing key pair
218  4 String signer = "saws";
219  4 KeyStore signKeystore = null;
220  4 try{
221  4 signKeystore = KeyStore.getInstance(KeyStore.getDefaultType()); //"JKS"
222  4 try {
223  4 signKeystore.load(new BufferedInputStream(
224    new FileInputStream(signingKeyfile)), sawsPW.toCharArray());
225    } catch (IOException e) {
226  0 this.showMessage("Reading signing keystore error. The signing keystore has been tampered with.",
227    SAWSTextOutputCallback.ERROR);
228    //System.err.println("Reading signing keystore error. The signing keystore has been tampered with.");
229  0 if (debugLevel >= SAWSConstant.ErrorInfo) {
230  0 sawsDebugLog.write(e.toString());
231    }
232  0 System.exit(-1);
233    }
234   
235  4 sawsSigningPrivateKey = (PrivateKey) signKeystore.getKey(signer, sawsPW.toCharArray());
236  4 sawsSigCertificate = signKeystore.getCertificate(signer);
237   
238  4 signingAlgName = SAWSConstant.HASH_ALG_NAMES[this.hashAlgorithm]
239    + "with"+sawsSigCertificate.getPublicKey().getAlgorithm();
240   
241  4 baSigningPublicKeyCert = sawsSigCertificate.getEncoded();
242  4 sawsSigningPublicKey = sawsSigCertificate.getPublicKey();
243   
244  4 java.security.cert.Certificate caCert = signKeystore.getCertificate("rootca");
245  4 if( (caCert==null) || (rootCA == null) ) {
246  0 this.showMessage(
247    "The rootCA PKC is missing in the SAWS configuration file or in the signing keystore."
248    + "\nSAWS will stop.", SAWSTextOutputCallback.ERROR);
249   
250    /*Object[] options = { "Stop"};
251    int select = JOptionPane.showOptionDialog(null,
252    "The rootCA PKC is missing in the SAWS configuration file or in the signing keystore." +
253    "\nSAWS will stop."
254    , "Warning",
255    JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
256    null, options, options[0]);*/
257    //if ( select == 0) {
258  0 System.exit(-1);
259    //}
260   
261    //rootCAPublicKey = sawsSigningPublicKey;
262    } else {
263  4 rootCAPublicKey = caCert.getPublicKey();
264    }
265   
266    } catch (Exception e2){
267  0 this.showMessage("Something wrong with signing keystore reading.",
268    SAWSTextOutputCallback.ERROR);
269   
270    //System.err.println("Something wrong with signing keystore reading.");
271  0 if (debugLevel >= SAWSConstant.ErrorInfo)
272    //adding log4j logging
273  0 sawsDebugLog.write(e2.toString());
274  0 System.exit(-1);
275    }
276   
277    // read SAWS encryption key pair
278  4 KeyStore encKeystore = null;
279  4 try{
280  4 encKeystore = KeyStore.getInstance(KeyStore.getDefaultType()); //"JKS"
281  4 encKeystore.load(new BufferedInputStream(
282    new FileInputStream(encryptionKeyfile)), sawsEncPW.toCharArray());
283  4 sawsEncryptionPrivateKey = (PrivateKey) encKeystore.getKey(signer, sawsEncPW.toCharArray());
284  4 sawsEncCertificate = encKeystore.getCertificate(signer);
285   
286  4 sawsEncryptionPublicKey = sawsEncCertificate.getPublicKey();
287    } catch(Exception e2){
288  0 this.showMessage("Something wrong with encryption keystore reading.",
289    SAWSTextOutputCallback.ERROR);
290   
291    //System.err.println("Something wrong with encryption keystore reading.");
292  0 if (debugLevel >= SAWSConstant.ErrorInfo)
293    //adding log4j logging
294  0 sawsDebugLog.write(e2.toString());
295  0 System.exit(-1);
296    }
297   
298    // get VT PK
299  4 try{
300  4 FileInputStream fis = new FileInputStream(vtPKC);
301  4 BufferedInputStream bis = new BufferedInputStream(fis);
302  4 java.security.cert.CertificateFactory cf = null;
303  4 cf = java.security.cert.CertificateFactory.getInstance("X.509");
304  4 java.security.cert.Certificate certTemp = cf.generateCertificate(bis);
305   
306  4 vtEncryptionPublicKey = certTemp.getPublicKey();
307    } catch (Exception e2) {
308  0 this.showMessage("SAWS VT encryption key is not correct.",
309    SAWSTextOutputCallback.ERROR);
310   
311    //System.err.println("SAWS VT encryption key is not correct.");
312  0 if (debugLevel >= SAWSConstant.ErrorInfo)
313    //adding log4j logging
314  0 sawsDebugLog.write(e2.toString());
315    }
316   
317   
318    }
319   
 
320  28 toggle public PublicKey getrootCAPublicKey (){
321  28 return rootCAPublicKey;
322    }
323   
 
324  11 toggle public PublicKey getvtEncryptionPublicKey(){
325  11 return vtEncryptionPublicKey;
326    }
327   
 
328  11 toggle public PublicKey getsawsEncryptionPublicKey(){
329  11 return sawsEncryptionPublicKey;
330    }
331   
 
332  56 toggle public PrivateKey getsawsEncryptionPrivateKey(){
333  56 return sawsEncryptionPrivateKey;
334    }
335   
 
336  11 toggle public PrivateKey getsawsSigningPrivateKey(){
337  11 return sawsSigningPrivateKey;
338    }
339   
 
340  0 toggle public PublicKey getsawsSigningPublicKey(){
341  0 return sawsSigningPublicKey;
342    }
343   
 
344  11 toggle public byte[] getbaSigningPublicKeyCert(){
345  11 return baSigningPublicKeyCert;
346    }
347   
 
348  0 toggle public String getsigningAlgName(){
349  0 return signingAlgName;
350    }
351   
 
352  4 toggle public SecretKey getsawsTCBSecretKey(){
353  4 sawsTCBSecretKey = generateSecretKey(sawsPW); // for writing and reading lastSN file
354  4 return sawsTCBSecretKey;
355    }
356   
 
357  4 toggle public PBEParameterSpec getparamSpec(){
358  4 byte[] salt = { (byte) 0x11, (byte) 0x23, (byte) 0x53, (byte) 0x65,
359    (byte) 0xbc, (byte) 0xef, (byte) 0xf1, (byte) 0x34 };
360  4 paramSpec = new PBEParameterSpec(salt, 10);
361  4 return paramSpec;
362    }
363   
364    /**
365    * This method generates a symmetric key based on a password.
366    *
367    * @param password String is the password used to generate the symmetric key.
368    */
 
369  4 toggle private SecretKey generateSecretKey(String password){
370  4 SecretKey sk = null;
371  4 try {
372  4 PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
373  4 SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
374  4 sk = kf.generateSecret(keySpec);
375    } catch (Exception e){
376  0 this.showMessage("Error when generating PBE TCBSecretKey!",
377    SAWSTextOutputCallback.ERROR);
378    //System.err.println("Error when generating PBE TCBSecretKey!");
379  0 if (debugLevel >= SAWSConstant.ErrorInfo){
380    //adding log4j logging
381  0 sawsDebugLog.write(e.toString());
382    }
383  0 return null;
384    }
385  4 return sk;
386    }
387   
388   
389    /**
390    * This method is to create a randomised password
391    *
392    * @param password input string
393    *
394    * @return String randomised password.
395    */
 
396  14 toggle private String generateRandomPW(String password){
397  14 java.security.MessageDigest firstHash = null;
398  14 try{
399  14 firstHash = java.security.MessageDigest.getInstance("SHA1");
400    } catch (Exception e2) {
401  0 if (debugLevel >= SAWSConstant.ErrorInfo)
402    //adding log4j logging
403  0 sawsDebugLog.write(e2.toString());
404    }
405   
406  14 byte[] sawsHash = null;
407   
408  14 String temp = password;
409  154 for (int i=0; i<10; ++i){
410  140 sawsHash = firstHash.digest(temp.getBytes()); // we can do more in the future.
411  140 temp = new String(sawsHash);
412    }
413  14 String pw = new sun.misc.BASE64Encoder().encode(sawsHash);
414   
415  14 return pw;
416    }
417   
418    /*
419    private String getCertificateData(byte purpose) {
420    String data = null;
421    //CreateCertificateDialog dialog = new CreateCertificateDialog(purpose);
422    //dialog.setVisible(true);
423    this.cbs = new Callback[1];
424    this.cbs[0] = new CertificateDataCallback(purpose);
425   
426   
427    try {
428    this.callbackHandler.handle(this.cbs);
429    } catch (Exception e) {
430    sawsDebugLog.write(e);
431    }
432    CertificateData cd = ((CertificateDataCallback)this.cbs[0]).getCertData();
433    //if (dialog.getSelectedOption() == CreateCertificateDialog.CONFIRM) {
434    if (cd != null) {
435    StringBuffer temp = new StringBuffer();
436    //temp.append("-keyalg \"" + dialog.getEncAlgorithm() + "\" ");
437    //temp.append("-keysize " + dialog.getKeySize() + " ");
438    //String dname = dialog.getSubjectName();
439    temp.append("-keyalg \"" + cd.getAlgorithm() + "\" ");
440    temp.append("-keysize " + cd.getKeySize() + " ");
441    String dname = cd.toSubjectName();
442    if (!dname.equals("")) {
443    temp.append("-dname \"" + dname + "\" ");
444    }
445    temp.append("-validity " + cd.getValidity() + " ");
446    data = new String(temp);
447    }
448   
449    return (data);
450    }*/
451   
452   
453    /*
454    * This method is to create a keystore
455    *
456    * @param keystoreLocation is the path for the keystore.
457    * @param pw is the password used for protecting the keystores.
458    *
459    * @return 0 for success.
460    *
461    private boolean createKeystoreByKeytool(String keystoreLocation, String pw, String certificateData){
462   
463   
464    boolean created = false;
465    //if (certificateData != null) {
466    StringBuffer commandLine =
467    new StringBuffer("keytool -genkey -alias saws " + certificateData);
468    commandLine.append(" -keystore " + keystoreLocation + " -storepass " + pw
469    + " -keypass " + pw);
470    try {
471    Process p = Runtime.getRuntime().exec(commandLine.toString());
472    created = true;
473    } catch (Exception err) {
474    if (debugLevel >= SAWSConstant.ErrorInfo)
475    //err.printStackTrace(System.err);
476    //adding log4j logging
477    sawsDebugLog.write(err.toString());
478    created = false;
479    }
480    //}
481    //System.out.println("\nThe new encryption keystore has been created. ");
482    return created;
483    }*/
484   
485    /**
486    * This method is to create a keystore using bouncy castle API
487    *
488    * @param keystoreLocation is the path for the keystore.
489    * @param pw is the password used for protecting the keystores.
490    *
491    * @return 0 for success.
492    */
 
493  2 toggle private boolean createKeystore(String keystoreLocation, String pw, CertificateData certificateData) {
494  2 KeyPairGenerator kpg = null; //to generate the private and public keys
495  2 X509Certificate cert = null; //represents the certificate generated from the public key
496  2 KeyPair kp = null; //the key pair generated
497  2 KeyStore ks = null;
498  2 Security.addProvider(new BouncyCastleProvider()); //add the BouncyCastle provider
499  2 BufferedOutputStream bos = null; // OutputStream to write the keystore file
500  2 boolean created = false;
501   
502  2 try {
503  2 kpg = KeyPairGenerator.getInstance(certificateData.getAlgorithm());
504  2 kpg.initialize(certificateData.getKeySize());
505  2 kp = kpg.genKeyPair();
506    } catch (NoSuchAlgorithmException e) {
507  0 this.showMessage("Invalid encryption algorithm for key pair generation.", SAWSTextOutputCallback.ERROR);
508  0 if (this.debugLevel >= SAWSConstant.ErrorInfo) {
509  0 this.sawsDebugLog.write("Invalid encryption algorithm for key pair generation.");
510    }
511  0 return false;
512    }
513   
514  2 X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
515  2 X500Principal dn = new X500Principal(certificateData.toSubjectName());
516  2 certGen.setSerialNumber(new BigInteger("1"));
517  2 certGen.setIssuerDN(dn);
518  2 certGen.setNotBefore(new Date());
519   
520  2 Calendar c = Calendar.getInstance();
521  2 c.setLenient(false);
522  2 c.add(Calendar.DATE, certificateData.getValidity());
523   
524  2 certGen.setNotAfter(c.getTime());
525  2 c = null;
526  2 certGen.setSubjectDN(dn);
527  2 certGen.setPublicKey(kp.getPublic());
528  2 certGen.setSignatureAlgorithm("SHA1with" + certificateData.getAlgorithm());
529   
530   
531  2 try {
532  2 cert = certGen.generate(kp.getPrivate(), "BC");
533    } catch (Exception e) {
534    //this.showMessage("Error creating self-signed certificate.", SAWSTextOutputCallback.ERROR);
535  0 if (this.debugLevel >= SAWSConstant.ErrorInfo) {
536  0 this.sawsDebugLog.write("Error creating self-signed certificate. " + e);
537    }
538  0 return false;
539    }
540   
541  2 try {
542  2 if (cert != null) {
543  2 ks = KeyStore.getInstance("JKS");
544  2 try {
545  2 ks.load(null, null);
546    } catch (Exception e) {
547    //this.showMessage("Error creating keystore.", SAWSTextOutputCallback.ERROR);
548  0 if (this.debugLevel >= SAWSConstant.ErrorInfo) {
549  0 this.sawsDebugLog.write("Error creating keystore: Keystore instance could not be initialized.");
550    }
551  0 return false;
552    }
553  2 ks.setCertificateEntry("saws", cert);
554  2 Certificate[] chain = {cert};
555  2 ks.setKeyEntry("saws", kp.getPrivate(), pw.toCharArray(), chain);
556    } else {
557    //this.showMessage("Public key certificate could not be created.", SAWSTextOutputCallback.WARNING);
558  0 if (this.debugLevel >= SAWSConstant.WarningInfo) {
559  0 this.sawsDebugLog.write("Public key certificate could not be created.");
560    }
561  0 return false;
562    }
563    } catch (KeyStoreException e) {
564  0 if (this.debugLevel >= SAWSConstant.ErrorInfo) {
565  0 this.sawsDebugLog.write("Error creating keystore: " + e.getMessage());
566    }
567  0 return false;
568    }
569   
570  2 try {
571  2 bos = new BufferedOutputStream(new FileOutputStream(new File(keystoreLocation)));
572    } catch (FileNotFoundException e) {
573  0 if (this.debugLevel >= SAWSConstant.ErrorInfo) {
574  0 this.sawsDebugLog.write("Error creating keystore: file was not created or not found.");
575    }
576  0 return false;
577    }
578   
579  2 try {
580  2 ks.store(bos, pw.toCharArray());
581  2 created = true;
582    } catch (Exception e) {
583    //this.showMessage("Error writing keystore to file.", SAWSTextOutputCallback.ERROR);
584  0 if (this.debugLevel >= SAWSConstant.ErrorInfo) {
585  0 this.sawsDebugLog.write("Error writing keystore to file: " + e.getMessage());
586    }
587  0 return false;
588    }
589  2 return created;
590    }
591   
592    /**
593    * Method that creates public key certificate request file, to be signed by a
594    * Certificate Authority.
595    */
 
596  0 toggle public void outputPKCRequest(){
597  0 signingKeyfile = new File( signingKeystoreLocation);
598  0 if ( !signingKeyfile.exists() ) {
599  0 this.showMessage("The SAWS signing keystore doesn't exist. Please first use SAWS to create a signing keystore. ",
600    SAWSTextOutputCallback.WARNING);
601    //System.out.println("The SAWS signing keystore doesn't exist. Please first use SAWS to create a signing keystore. ");
602  0 System.exit(-1);
603    }
604    //System.out.println("Now please input the password for the signing keystore in the pop-up window:");
605  0 sawsPW = getSAWSPassword3Attempts(signingKeystoreLocation, numberOfPasswordShares, "signing", false);
606  0 if (sawsPW == null ){
607  0 this.showMessage("The password to the signing keystore is wrong. SAWS will stop.",
608    SAWSTextOutputCallback.WARNING);
609    //System.out.println("The password to the signing keystore is wrong. SAWS will stop.");
610  0 System.exit(-1);
611    }
612   
613  0 boolean b1 = createPKCReqest(signingKeystoreLocation, sawsPW);
614  0 if (b1) {
615  0 this.showMessage("The SAWS PKC request file sawsRequest.csr in the "
616    + "current directory has been created successfully."
617    + "\nPlease pass it to a RootCA for issuing a PKC.",
618    SAWSTextOutputCallback.INFORMATION);
619    //System.out.println("The SAWS PKC request file sawsRequest.csr in the current directory has been created successfully." +
620    // "\nPlease pass it to a RootCA for issuing a PKC.");
621    } else {
622  0 this.showMessage("There is something wrong with creating the SAWS PKC request file. ",
623    SAWSTextOutputCallback.WARNING);
624    //System.out.println("There is something wrong with creating the SAWS PKC request file. ");
625    }
626   
627   
628    }
629   
630    /**
631    * Method to generate the public key certificate request file for SAWS
632    * encryption certificate.
633    *
634    * @param keystoreLocation The path to the key store.
635    * @param pw The key store password.
636    * @return True, if the request file has been created; False, otherwise.
637    */
 
638  0 toggle private boolean createPKCReqest(String keystoreLocation, String pw) {
639  0 boolean created = false;
640  0 Security.addProvider(new BouncyCastleProvider());
641  0 KeyStore ks = null;
642   
643   
644  0 try {
645  0 ks = KeyStore.getInstance(KeyStore.getDefaultType());
646  0 ks.load(new BufferedInputStream(new FileInputStream(keystoreLocation)), pw.toCharArray());
647    } catch (Exception e) {
648  0 if (this.debugLevel >= SAWSConstant.ErrorInfo) {
649  0 this.sawsDebugLog.write("Error reading keystore file when creating PKC request: " + e.getMessage());
650    }
651  0 return false;
652    }
653  0 Certificate cert = null;
654  0 try {
655  0 cert = ks.getCertificate("saws");
656    } catch (KeyStoreException e) {
657  0 if (this.debugLevel >= SAWSConstant.ErrorInfo) {
658  0 this.sawsDebugLog.write("Error reading certificate from keystore file when creating PKC request: " + e.getMessage());
659    }
660  0 return false;
661    }
662  0 PKCS10CertificationRequest request = null;
663  0 try {
664  0 request =
665    new PKCS10CertificationRequest(
666    "SHA1withRSA", new X500Principal(((X509Certificate)cert).getSubjectDN().toString()),
667    cert.getPublicKey(), null, (PrivateKey)ks.getKey("saws", pw.toCharArray()));
668   
669  0 byte buf[] = request.getEncoded();
670   
671  0 StringBuffer sb = new StringBuffer("-----BEGIN NEW CERTIFICATE REQUEST-----\n");
672  0 sb.append(new sun.misc.BASE64Encoder().encode(buf));
673  0 sb.append("\n-----END NEW CERTIFICATE REQUEST-----\n");
674   
675  0 OutputStreamWriter wr = new OutputStreamWriter(new FileOutputStream("sawsRequest.csr"));
676  0 wr.write(new String(sb));
677  0 wr.flush();
678  0 wr.close();
679   
680  0 created = true;
681   
682    } catch (Exception e) {
683  0 if (this.debugLevel >= SAWSConstant.ErrorInfo) {
684  0 this.sawsDebugLog.write("Error creating PKC request file: " + e.getMessage());
685    }
686  0 return false;
687    }
688   
689  0 return created;
690    }
691   
692    /*
693    private boolean createPKCReqestByKeytool(String keystoreLocation, String pw){
694   
695    // keytool -certreq -alias tomcat-server -keyalg RSA -file tomcat.csr -keystore tomcat.keystore -storepass changeit
696    StringBuffer commandLine =
697    new StringBuffer("keytool -certreq -keyalg \"RSA\" -alias saws -file sawsRequest.csr");
698    commandLine.append(" -keystore " + keystoreLocation + " -storepass " + pw );
699   
700    try {
701    Process p = Runtime.getRuntime().exec(commandLine.toString());
702    } catch (Exception err) {
703    if (debugLevel >= SAWSConstant.ErrorInfo)
704    //adding log4j logging
705    sawsDebugLog.write(err.toString());
706    return false;
707    }
708    return true;
709   
710    } */
711   
712    /**
713    * Method that exports the Public Key Certificate in the signing key store.
714    */
 
715  1 toggle public void exportSigningPKC() {
716  1 signingKeyfile = new File( signingKeystoreLocation);
717  1 if ( !signingKeyfile.exists() ) {
718  0 this.showMessage("The SAWS signing keystore doesn't exist. Please first use SAWS to create a signing keystore. ",
719    SAWSTextOutputCallback.WARNING);
720    //System.out.println("The SAWS signing keystore doesn't exist. Please first use SAWS to create a signing keystore. ");
721  0 System.exit(-1);
722    }
723    //System.out.println("Now please input the password for the signing keystore in the pop-up window:");
724  1 sawsPW = getSAWSPassword3Attempts(signingKeystoreLocation, numberOfPasswordShares, "signing", false);
725  1 if (sawsPW == null ){
726  0 this.showMessage("The password to the signing keystore is wrong. SAWS will stop.",
727    SAWSTextOutputCallback.WARNING);
728    //System.out.println("The password to the signing keystore is wrong. SAWS will stop.");
729  0 System.exit(-1);
730    }
731   
732  1 boolean b1 = exportPKC(signingKeystoreLocation, sawsPW);
733  1 if (b1) {
734  1 this.showMessage("The SAWS Signing PKC file sawsSigningPKC.crt in the current directory has been exported successfully.",
735    SAWSTextOutputCallback.INFORMATION);
736    //System.out.println("The SAWS Signing PKC file sawsSigningPKC.crt in the current directory has been exported successfully.");
737    } else {
738  0 this.showMessage("There is something wrong with exporting the SAWS Signing PKC file.",
739    SAWSTextOutputCallback.WARNING);
740    //System.out.println("There is something wrong with exporting the SAWS Signing PKC file.");
741    }
742    }
743   
744    /**
745    * Auxiliar method that exports the Public Key Certificate in the specified key store.
746    *
747    * @param keystoreLocation The path to the key store.
748    * @param pw The key store password.
749    * @return True, if the PKC file has been exported; False, otherwise.
750    */
 
751  1 toggle private boolean exportPKC(String keystoreLocation, String pw) {
752  1 boolean created = false;
753  1 KeyStore ks = null;
754   
755   
756  1 try {
757  1 ks = KeyStore.getInstance(KeyStore.getDefaultType());
758  1 ks.load(new BufferedInputStream(new FileInputStream(keystoreLocation)), pw.toCharArray());
759    } catch (Exception e) {
760  0 if (this.debugLevel >= SAWSConstant.ErrorInfo) {
761  0 this.sawsDebugLog.write("Error reading keystore file when exporting PKC: " + e.getMessage());
762    }
763  0 return false;
764    }
765  1 Certificate cert = null;
766  1 try {
767  1 cert = ks.getCertificate("saws");
768    } catch (KeyStoreException e) {
769  0 if (this.debugLevel >= SAWSConstant.ErrorInfo) {
770  0 this.sawsDebugLog.write("Error reading certificate from keystore file when exporting PKC: " + e.getMessage());
771    }
772  0 return false;
773    }
774   
775  1 try {
776  1 StringBuffer sb = new StringBuffer("-----BEGIN CERTIFICATE-----\n");
777  1 sb.append(new sun.misc.BASE64Encoder().encode(cert.getEncoded()));
778  1 sb.append("\n-----END CERTIFICATE-----\n");
779   
780  1 OutputStreamWriter wr = new OutputStreamWriter(new FileOutputStream("sawsSigningPKC.crt"));
781  1 wr.write(new String(sb));
782  1 wr.flush();
783  1 wr.close();
784   
785  1 created = true;
786   
787    } catch (Exception e) {
788  0 if (this.debugLevel >= SAWSConstant.ErrorInfo) {
789  0 this.sawsDebugLog.write("Error exporting PKC file: " + e.getMessage());
790    }
791  0 return false;
792    }
793   
794  1 return created;
795    }
796   
797    /*
798    private boolean exportSigningPKCByKeytool(String keystoreLocation, String pw) {
799   
800    //keytool -v -rfc –export -alias saws -file saws.crt -keystore signing.keystore -storepass changeit
801    StringBuffer commandLine =
802    new StringBuffer("keytool -v -rfc -export -alias saws -file sawsSigningPKC.crt");
803    commandLine.append(" -keystore " + keystoreLocation + " -storepass " + pw );
804   
805    try {
806    Process p = Runtime.getRuntime().exec(commandLine.toString());
807    }
808    catch (Exception err) {
809    if (debugLevel >= SAWSConstant.ErrorInfo)
810    //adding log4j logging
811    sawsDebugLog.write(err.toString());
812    return false;
813    }
814    return true;
815   
816    }
817    */
818   
819    /**
820    * Method that imports the Public Key Certificate signed by a Certificate
821    * Authority to the signing key store.
822    */
 
823  0 toggle public void importSigningPKC(){
824  0 InputStreamReader is = new InputStreamReader(System.in);
825  0 BufferedReader systemIn = new BufferedReader(is);
826   
827  0 this.cbs = new Callback[1];
828  0 this.cbs[0] = new SAWSTextInputCallback("Please input the SAWS PKC file name:", "SAWSPKCFileName");
829   
830  0 try {
831  0 this.callbackHandler.handle(this.cbs);
832    } catch (Exception e) {
833  0 System.err.println(e.getMessage());
834  0 sawsDebugLog.write(e);
835    }
836  0 String sIn = ((SAWSTextInputCallback)this.cbs[0]).getText();
837  0 if (sIn == null) {
838  0 this.showMessage("The file name is null. Please restart SAWS and type a valid file name."
839    + "\nSAWS will stop.",
840    SAWSTextOutputCallback.WARNING);
841  0 System.exit(-1);
842    }
843   
844  0 File sPKCFile = new File(sIn);
845   
846  0 if ( !sPKCFile.exists() ) {
847  0 this.showMessage("This file doesn't exist. SAWS will stop. ",
848    SAWSTextOutputCallback.WARNING);
849    //System.out.println("This file doesn't exist. SAWS will stop. ");
850  0 System.exit(-1);
851    }
852    //System.out.println("Now please input the password for the signing keystore in the pop-up window:");
853   
854  0 sawsPW = getSAWSPassword3Attempts(signingKeystoreLocation, numberOfPasswordShares, "signing", false);
855  0 if (sawsPW == null ){
856  0 this.showMessage("The password to the signing keystore is wrong. SAWS will stop.",
857    SAWSTextOutputCallback.WARNING);
858    //System.out.println("The password to the signing keystore is wrong. SAWS will stop.");
859  0 System.exit(-1);
860    }
861   
862    //boolean b1 = importPKCByKeytool(signingKeystoreLocation, sawsPW, sIn );
863  0 boolean b1 = importPKC(signingKeystoreLocation, sawsPW, sIn, "saws");
864  0 if (b1) {
865  0 this.showMessage("The SAWS PKC has been imported into the signing keystore.",
866    SAWSTextOutputCallback.INFORMATION);
867    //System.out.println("The SAWS PKC has been imported into the signing keystore." );
868    } else {
869  0 this.showMessage("There is something wrong when importing the SAWS PKC into the signing keystore.",
870    SAWSTextOutputCallback.WARNING);
871    //System.out.println("There is something wrong when importing the SAWS PKC into the signing keystore. ");
872    }
873    }
874   
875    /**
876    * Method to import a certificate to a specified key store.
877    *
878    * @param keystoreLocation The path to the key store file.
879    * @param pw The key store password.
880    * @param pkcFile The Public Key certificate to be imported.
881    * @param alias The alias for the certificate in the keystore.
882    *
883    * @return True, if the PKC file has been imported; False, otherwise.
884    */
 
885  1 toggle private boolean importPKC(String keystoreLocation, String pw,
886    String pkcFile, String alias) {
887  1 boolean imported = false;
888  1 KeyStore ks = null;
889   
890   
891  1 try {
892  1 ks = KeyStore.getInstance(KeyStore.getDefaultType());
893  1 ks.load(new BufferedInputStream(new FileInputStream(keystoreLocation)), pw.toCharArray());
894    } catch (Exception e) {
895  0 if (this.debugLevel >= SAWSConstant.ErrorInfo) {
896  0 this.sawsDebugLog.write("Error reading keystore file when exporting PKC: " + e.getMessage());
897    }
898  0 return false;
899    }
900   
901  1 Certificate cert = null;
902  1 try {
903  1 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(pkcFile));
904   
905  1 CertificateFactory cf = CertificateFactory.getInstance("X.509");
906   
907  2 while (bis.available() > 0) {
908  1 cert = cf.generateCertificate(bis);
909    }
910    } catch (Exception e) {
911  0 if (this.debugLevel >= SAWSConstant.ErrorInfo) {
912  0 this.sawsDebugLog.write("Error reading certificate from file when importing PKC: " + e.getMessage());
913    }
914  0 return false;
915    }
916   
917  1 BufferedOutputStream bos = null;
918  1 try {
919  1 bos = new BufferedOutputStream(new FileOutputStream(new File(keystoreLocation)));
920    } catch (FileNotFoundException e) {
921  0 if (this.debugLevel >= SAWSConstant.ErrorInfo) {
922  0 this.sawsDebugLog.write("Error accessing key store file when importing certificate: "
923    + e.getMessage());
924    }
925  0 return false;
926    }
927   
928  1 try {
929  1 ks.setCertificateEntry(alias, cert);
930  1 ks.store(bos, pw.toCharArray());
931  1 imported = true;
932    } catch (Exception e) {
933  0 if (this.debugLevel >= SAWSConstant.ErrorInfo) {
934  0 this.sawsDebugLog.write("Error writing keystore to file when importing key store: " + e.getMessage());
935    }
936  0 return false;
937    }
938   
939  1 return imported;
940    }
941   
942    /*
943    private boolean importPKCByKeytool(String keystoreLocation, String pw, String certname){
944   
945    // keytool -import -alias saws -trustcacerts -file saws.crt -keystore signing.keystore -storepass changeit
946    StringBuffer commandLine =
947    new StringBuffer("keytool -import -noprompt -alias saws -trustcacerts -file " + certname );
948    commandLine.append(" -keystore " + keystoreLocation + " -storepass " + pw );
949   
950    try {
951    Process p = Runtime.getRuntime().exec(commandLine.toString());
952    }
953    catch (Exception err) {
954    if (debugLevel >= SAWSConstant.ErrorInfo)
955    //err.printStackTrace(System.err);
956    //adding log4j logging
957    sawsDebugLog.write(err.toString());
958    return false;
959    }
960    return true;
961   
962    }*/
963   
964    /**
965    * Method that creates the SAWS's encryption key store.
966    */
 
967  1 toggle public void createEncryptionKeystore(){
968  1 InputStreamReader is = new InputStreamReader(System.in);
969    // BufferedReader systemIn = new BufferedReader(is);
970   
971  1 encryptionKeyfile = new File( encryptionKeystoreLocation);
972   
973  1 if ( encryptionKeyfile.exists() ) {
974    //System.out.println("Now please input the password for the encryption keystore in the pop-up window:");
975  1 sawsPW = getSAWSPasswordOnce(numberOfEncPasswordShares, "encryption", false);
976  1 boolean tempB = checkKeystorePassword(encryptionKeystoreLocation, sawsPW );
977   
978  1 String[] options = {"Create new encryption keystore", "Stop SAWS"};
979   
980  1 int selection = this.createConfirmCallback(
981    "The encryption keystore already exists, \nand the password to the encryption keystore is " + tempB + "."
982    + "\n\nOption 1: SAWS will create a new encryption keystore and overwrite the old one. "
983    + "\nOption 2: SAWS will stop.\n", options, SAWSChoiceCallback.WARNING, "ExistingEncKeystore");
984  1 if ( selection == 1) {//(sIn.compareTo("2") == 0) ) {
985  0 this.showMessage("SAWS stoped.", SAWSTextOutputCallback.WARNING);
986  0 System.exit(0);
987    } else {
988  1 boolean b1 = encryptionKeyfile.delete();
989  1 if (b1) {
990  1 this.showMessage(encryptionKeystoreLocation + " has been deleted. ",
991    SAWSTextOutputCallback.INFORMATION);
992    //System.out.println(encryptionKeystoreLocation + " has been deleted. ");
993    } else {
994  0 this.showMessage(encryptionKeystoreLocation + " can't be deleted. ",
995    SAWSTextOutputCallback.WARNING);
996    //System.out.println(encryptionKeystoreLocation + " can't be deleted. ");
997  0 System.exit(-1);
998    }
999    }
1000    }
1001  1 sawsPW = null;
1002   
1003    //System.out.println("Now please input the data for the digital certificate on the keystore in the pop-up window:");
1004    //String certificateData = this.getCertificateData(SAWSConstant.ENCRYPTION_PURPOSE);
1005  1 this.cbs = new Callback[1];
1006  1 this.cbs[0] = new CertificateDataCallback(SAWSConstant.ENCRYPTION_PURPOSE);
1007   
1008   
1009  1 try {
1010  1 this.callbackHandler.handle(this.cbs);
1011    } catch (Exception e) {
1012  0 sawsDebugLog.write(e);
1013    }
1014  1 CertificateData cd = ((CertificateDataCallback)this.cbs[0]).getCertData();
1015   
1016  1 if (cd == null) {
1017  0 this.showMessage("The process of creating the encryption keystore has been canceled. Keystore was not created.",
1018    SAWSTextOutputCallback.WARNING);
1019    } else {
1020  1 sawsPW = getSAWSPasswordOnce(numberOfEncPasswordShares, "encryption", true);
1021   
1022  1 boolean b1 = createKeystore(encryptionKeystoreLocation, sawsPW, cd);
1023  1 if (b1) {
1024  1 this.showMessage(encryptionKeystoreLocation + " has been created successfully.",
1025    SAWSTextOutputCallback.INFORMATION);
1026    //System.out.println(encryptionKeystoreLocation + " has been created successfully.");
1027    } else {
1028  0 this.showMessage("There is something wrong with creating " + encryptionKeystoreLocation,
1029    SAWSTextOutputCallback.WARNING);
1030    //System.out.println("There is something wrong with creating " + encryptionKeystoreLocation);
1031    }
1032    }
1033   
1034    /*if (certificateData == null) {
1035    this.showMessage("The process of creating the encryption keystore has been canceled. Keystore was not created.",
1036    SAWSTextOutputCallback.WARNING);
1037    //System.out.println("The process of creating the encryption keystore has been canceled. Keystore not created.");
1038    } else {
1039    sawsPW = getSAWSPasswordOnce(numberOfEncPasswordShares, "encryption", true);
1040   
1041    boolean b1 = createKeystoreByKeytool(encryptionKeystoreLocation, sawsPW, certificateData);
1042    if (b1) {
1043    this.showMessage(encryptionKeystoreLocation + " has been created successfully.",
1044    SAWSTextOutputCallback.INFORMATION);
1045    //System.out.println(encryptionKeystoreLocation + " has been created successfully.");
1046    } else {
1047    this.showMessage("There is something wrong with creating " + encryptionKeystoreLocation,
1048    SAWSTextOutputCallback.WARNING);
1049    //System.out.println("There is something wrong with creating " + encryptionKeystoreLocation);
1050    }
1051    }*/
1052   
1053    }
1054   
1055    /**
1056    * Method that creates the SAWS's signing key store.
1057    */
 
1058  1 toggle public void createSigningKeystore(){
1059  1 InputStreamReader is = new InputStreamReader(System.in);
1060    //BufferedReader systemIn = new BufferedReader(is);
1061   
1062  1 signingKeyfile = new File( signingKeystoreLocation);
1063   
1064  1 if ( signingKeyfile.exists() ) {
1065    //System.out.println("Now please input the password for the signing keystore in the pop-up window:");
1066  1 sawsPW = getSAWSPasswordOnce(numberOfPasswordShares, "signing", false);
1067  1 boolean tempB = checkKeystorePassword(signingKeystoreLocation, sawsPW );
1068   
1069  1 String[] options = {"Create new signing keystore", "Stop SAWS"};
1070   
1071  1 int selection = this.createConfirmCallback(
1072    "The signing keystore already exists, \nand the password to the signing keystore is " + tempB + "."
1073    + "\n\nOption 1: SAWS will create a new signing keystore and overwrite the old one. "
1074    + "\nOption 2: SAWS will stop.\n", options, SAWSChoiceCallback.WARNING, "ExistingSigKeystore");
1075   
1076  1 if ( selection == 1) {//(sIn.compareTo("2") == 0) ) {
1077  0 this.showMessage("SAWS stoped.", SAWSTextOutputCallback.WARNING);
1078    //System.out.println("SAWS stoped.");
1079  0 System.exit(0);
1080    } else {
1081  1 boolean b1 = signingKeyfile.delete();
1082  1 if (b1) {
1083  1 this.showMessage(signingKeystoreLocation + " has been deleted. ",
1084    SAWSTextOutputCallback.INFORMATION);
1085    //System.out.println(signingKeystoreLocation + " has been deleted. ");
1086    } else {
1087  0 this.showMessage(signingKeystoreLocation + " can't be deleted. ",
1088    SAWSTextOutputCallback.WARNING);
1089    //System.out.println(signingKeystoreLocation + " can't be deleted. ");
1090  0 System.exit(-1);
1091    }
1092    }
1093    }
1094   
1095  1 sawsPW = null;
1096   
1097  1 this.cbs = new Callback[1];
1098  1 this.cbs[0] = new CertificateDataCallback(SAWSConstant.SIGNING_PURPOSE);
1099   
1100   
1101  1 try {
1102  1 this.callbackHandler.handle(this.cbs);
1103    } catch (Exception e) {
1104  0 sawsDebugLog.write(e);
1105    }
1106  1 CertificateData cd = ((CertificateDataCallback)this.cbs[0]).getCertData();
1107   
1108  1 if (cd == null) {
1109  0 this.showMessage("The process of creating the signing keystore has been canceled. Keystore was not created.",
1110    SAWSTextOutputCallback.WARNING);
1111    //System.out.println("The process of creating the signing keystore has been canceled. Keystore was not created.");
1112    } else {
1113  1 sawsPW = getSAWSPasswordOnce(numberOfPasswordShares, "signing", true);
1114  1 boolean b1 = createKeystore(signingKeystoreLocation, sawsPW, cd);
1115  1 if (b1) {
1116  1 this.showMessage(signingKeystoreLocation + " has been created successfully.",
1117    SAWSTextOutputCallback.INFORMATION);
1118    //System.out.println(signingKeystoreLocation + " has been created successfully.");
1119    } else {
1120  0 this.showMessage("There is something wrong with creating " + signingKeystoreLocation,
1121    SAWSTextOutputCallback.WARNING);
1122    //System.out.println("There is something wrong with creating " + signingKeystoreLocation);
1123    }
1124    }
1125   
1126    /*String certificateData = this.getCertificateData(SAWSConstant.SIGNING_PURPOSE);
1127   
1128    if (certificateData == null) {
1129    this.showMessage("The process of creating the signing keystore has been canceled. Keystore was not created.",
1130    SAWSTextOutputCallback.WARNING);
1131    //System.out.println("The process of creating the signing keystore has been canceled. Keystore was not created.");
1132    } else {
1133    sawsPW = getSAWSPasswordOnce(numberOfPasswordShares, "signing", true);
1134    boolean b1 = createKeystoreByKeytool(signingKeystoreLocation, sawsPW, certificateData);
1135    if (b1) {
1136    this.showMessage(signingKeystoreLocation + " has been created successfully.",
1137    SAWSTextOutputCallback.INFORMATION);
1138    //System.out.println(signingKeystoreLocation + " has been created successfully.");
1139    } else {
1140    this.showMessage("There is something wrong with creating " + signingKeystoreLocation,
1141    SAWSTextOutputCallback.WARNING);
1142    //System.out.println("There is something wrong with creating " + signingKeystoreLocation);
1143    }
1144    }*/
1145   
1146    }
1147   
1148   
1149    /**
1150    * Method that imports the root CA certificate specified in SAWS's
1151    * configuration file (saws.xml).
1152    */
 
1153  1 toggle public void importRootCA() {
1154   
1155  1 InputStreamReader is = new InputStreamReader(System.in);
1156  1 BufferedReader systemIn = new BufferedReader(is);
1157    //System.out.println("Now please input the password for the signing keystore in the pop-up window:");
1158   
1159  1 sawsPW = getSAWSPassword3Attempts(signingKeystoreLocation, numberOfPasswordShares, "signing", false);
1160  1 if (sawsPW == null ){
1161  0 this.showMessage("The password to the signing keystore is wrong. SAWS will stop.",
1162    SAWSTextOutputCallback.WARNING);
1163    //System.out.println("The password to the signing keystore is wrong. SAWS will stop.");
1164  0 System.exit(-1);
1165    }
1166   
1167  1 boolean imported = this.importPKC(signingKeystoreLocation, sawsPW, rootCA, "rootca");
1168   
1169  1 if (imported) {
1170  1 this.showMessage("The root certificate has been imported successfully.",
1171    SAWSTextOutputCallback.INFORMATION);
1172    } else {
1173  0 this.showMessage("There is something wrong when importing the SAWS root CA certificate into the signing keystore."
1174    + "\nPlease check the path for the root certificate in the configuration file (saws.xml).",
1175    SAWSTextOutputCallback.WARNING);
1176    }
1177    /*
1178    // keytool -import -alias rootca -file rootca.crt -keystore signing.keystore -storepass changeit
1179    StringBuffer commandLine =
1180    new StringBuffer("keytool -import -alias rootca -noprompt -file " + rootCA );
1181    commandLine.append(" -keystore " + signingKeystoreLocation + " -storepass " + sawsPW );
1182   
1183    try {
1184    Process p = Runtime.getRuntime().exec(commandLine.toString());
1185    this.showMessage("The root certificate has been imported successfully.",
1186    SAWSTextOutputCallback.INFORMATION);
1187    }
1188    catch (Exception err) {
1189    if (debugLevel >= SAWSConstant.ErrorInfo) {
1190    sawsDebugLog.write(err.toString());
1191    }
1192    }*/
1193   
1194    }
1195   
1196    /**
1197    * Method that lists all the certificates in the signing key store.
1198    * The list of certificates will be displayed according to the
1199    * Callback handler specified in the configuration file (saws.xml).
1200    */
 
1201  0 toggle public void listSigningKeystore(){
1202  0 InputStreamReader is = new InputStreamReader(System.in);
1203  0 BufferedReader systemIn = new BufferedReader(is);
1204    //System.out.println("Now please input the password for the signing keystore in the pop-up window:");
1205   
1206  0 sawsPW = getSAWSPassword3Attempts(signingKeystoreLocation, numberOfPasswordShares, "signing", false);
1207  0 if (sawsPW == null ){
1208  0 this.showMessage("The password to the signing keystore is wrong. SAWS will stop.",
1209    SAWSTextOutputCallback.WARNING);
1210    //System.out.println("The password to the signing keystore is wrong. SAWS will stop.");
1211  0 System.exit(-1);
1212    }
1213   
1214  0 try {
1215    //Process p2 = Runtime.getRuntime().exec(
1216    // "keytool -list -v -keystore " + signingKeystoreLocation + " -storepass " + sawsPW);
1217    //BufferedReader input = new BufferedReader(new InputStreamReader(p2.getInputStream()));
1218    //String line = null;
1219   
1220  0 KeyStore ks = null;
1221  0 try {
1222  0 ks = KeyStore.getInstance("JKS");
1223    } catch (KeyStoreException kse) {
1224  0 this.showMessage("Fail when creating a keystore instance.", SAWSTextOutputCallback.ERROR);
1225    }
1226  0 try {
1227  0 ks.load(new FileInputStream(signingKeystoreLocation),
1228    sawsPW.toCharArray());
1229    } catch (IOException ioe) {
1230  0 this.showMessage("Signing keystore could not be found.", SAWSTextOutputCallback.ERROR);
1231    }
1232   
1233  0 StringBuffer certificates = new StringBuffer();
1234  0 for (Enumeration e = ks.aliases(); e.hasMoreElements() ;) {
1235  0 String alias = (String)e.nextElement();
1236  0 Certificate c = ks.getCertificate(alias);
1237  0 certificates.append("------ BEGINS Certificate: " + alias + " ------\n"
1238    + c.toString() + "\n------- ENDS Certificate: " + alias + " -------\n\n");
1239    }
1240   
1241   
1242   
1243    //while ((line = input.readLine()) != null) {
1244  0 this.showMessage(new String(certificates),
1245    SAWSTextOutputCallback.LONG_MESSAGE);
1246    //System.out.println(line);
1247    //}
1248    //input.close();
1249    } catch (Exception err) {
1250  0 if (debugLevel >= SAWSConstant.ErrorInfo) {
1251  0 sawsDebugLog.write(err);
1252    }
1253    }
1254   
1255    }
1256   
1257    /**
1258    * This method makes 3 (three) attempts of getting the SAWS password, i. e.,
1259    * the user has 3 (three) chances for typing the password correctly.
1260    *
1261    * @param keystoreLocation Path to the key store file.
1262    * @param numberOfPasswordShares Number of password shares for the keystore.
1263    * @param prompt The message to be displayed to the user.
1264    * @param newPassword Indicates if a new password has to be created or not.
1265    *
1266    * @return The password
1267    */
 
1268  10 toggle private String getSAWSPassword3Attempts(String keystoreLocation, int numberOfPasswordShares, String prompt, boolean newPassword){
1269  10 String pass = null;
1270  10 for (int j = 0; j<3; ++j) {
1271  10 pass = getSAWSPasswordOnce(numberOfPasswordShares, prompt, newPassword);
1272  10 boolean tempB = checkKeystorePassword(keystoreLocation, pass);
1273  10 if (tempB == true) {
1274  10 break;
1275  0 } else if (j<2) {
1276  0 this.showMessage("Password to the " + prompt
1277    + " keystore is wrong. \nPlease try your password again.",
1278    SAWSTextOutputCallback.ERROR);
1279   
1280  0 continue;
1281    } else {
1282  0 this.showMessage("Password to the " + prompt
1283    + " keystore is wrong. \nSAWS will stop.",
1284    SAWSTextOutputCallback.ERROR);
1285  0 return null;
1286    }
1287    }
1288  10 return pass;
1289    }
1290   
1291    /**
1292    * This method asks the user to input the password for SAWS.
1293    *
1294    * @param numberOfPasswordShares Number of password shares for the keystore.
1295    * @param prompt The message to be displayed to the user.
1296    * @param newPassword Indicates if a new password has to be created or not.
1297    *
1298    * @return The password
1299    */
 
1300  14 toggle private String getSAWSPasswordOnce(int numberOfPasswordShares, String prompt, boolean newPassword){
1301  14 String pass = null;
1302  14 StringBuffer passBuffer = new StringBuffer("");
1303  28 for (int i = 1; i <= numberOfPasswordShares; ++i){
1304  14 SAWSPasswordCallback pc = new SAWSPasswordCallback("Please input the password for the "
1305    + prompt + " keystore \nfrom SAWS administrator No. "
1306    + i + " out of " + numberOfPasswordShares + ":", numberOfPasswordShares, i, false, prompt);
1307  14 if (!newPassword) {
1308  12 this.cbs = new Callback[1];
1309  12 this.cbs[0] = pc;
1310    } else {
1311  2 this.cbs = new Callback[2];
1312  2 this.cbs[0] = pc;
1313  2 this.cbs[1] = new SAWSPasswordCallback("Please repeat the password for the "
1314    + prompt + " keystore \nfrom SAWS administrator No. "
1315    + i + " out of " + numberOfPasswordShares + ":", numberOfPasswordShares, i, false, prompt);
1316    }
1317   
1318   
1319  14 try {
1320  14 this.callbackHandler.handle(cbs);
1321    } catch (Exception e) {
1322  0 sawsDebugLog.write(e);
1323    }
1324   
1325  14 char[] pass1 = ((SAWSPasswordCallback)this.cbs[0]).getPassword();
1326  14 ((SAWSPasswordCallback)cbs[0]).clearPassword();
1327  14 if (newPassword) {
1328  2 char[] pass2 = ((SAWSPasswordCallback)this.cbs[1]).getPassword();
1329  2 ((SAWSPasswordCallback)cbs[1]).clearPassword();
1330  2 if (!Arrays.equals(pass1, pass2)) {
1331  0 this.showMessage("The password and the confirmation are not equal."
1332    + "\nSAWS will stop.", SAWSTextOutputCallback.ERROR);
1333  0 System.exit(-1);
1334    }
1335    }
1336  14 passBuffer.append(pass1);
1337    }
1338   
1339  14 String s2 = passBuffer.toString();
1340  14 pass = generateRandomPW(s2);
1341  14 return pass;
1342    }
1343   
1344    /**
1345    * Method that checks if the password for the keystore is valid.
1346    *
1347    * @param keystoreLocation The location of the keystore.
1348    * @param pw The Password
1349    * @return True if the password is valid, False, otherwise.
1350    */
 
1351  12 toggle private boolean checkKeystorePassword(String keystoreLocation, String pw) {
1352  12 KeyStore keystore = null;
1353  12 FileInputStream fis = null;
1354  12 try{
1355  12 fis = new FileInputStream(new File(keystoreLocation)) ;
1356  12 keystore = KeyStore.getInstance(KeyStore.getDefaultType());
1357  12 keystore.load( new BufferedInputStream( fis), pw.toCharArray() );
1358  12 fis.close();
1359    } catch(Exception e) {
1360  0 try {fis.close(); } catch (Exception e2){}
1361  0 if (debugLevel >= SAWSConstant.ErrorInfo) {
1362  0 sawsDebugLog.write(e.toString());
1363    }
1364  0 return false;
1365    }
1366  12 return true;
1367   
1368    }
1369   
1370    /**
1371    * Method to create the callback (SAWSTextOutputCallback) with the message to be
1372    * presented to the user and send it to the callback handler.
1373    *
1374    * @param message The message to be presented.
1375    * @param type The type of the message (SAWSTextOutputCallback.WARNING,
1376    * SAWSTextOutputCallback.ERROR, SAWSTextOutputCallback.INFORMATION,
1377    * SAWSTextOutputCallback.LONG_MESSAGE)
1378    */
 
1379  6 toggle private void showMessage(String message, int type) {
1380  6 this.cbs = new Callback[1];
1381  6 this.cbs[0] = new SAWSTextOutputCallback(type, message);
1382  6 try {
1383  6 this.callbackHandler.handle(this.cbs);
1384    }
1385    catch (Exception e) {
1386  0 System.err.println(e.getMessage());
1387  0 sawsDebugLog.write(e);
1388    }
1389    }
1390   
1391    /**
1392    * Method that creates a callback (SAWSChoiceCallback) that asks the user
1393    * to choose one option, and sends it to the callback handler.
1394    *
1395    * @param prompt The message to be presented to the user.
1396    * @param options The available options for the user.
1397    * @param type The type of the callback (Warning, Information, etc.)
1398    *
1399    * @return the selected option.
1400    */
 
1401  2 toggle private int createConfirmCallback(String prompt, String[] options, int type, String key) {
1402  2 this.cbs = new Callback[1];
1403  2 this.cbs[0] = new SAWSChoiceCallback(prompt, options, key, 0, type);
1404  2 try {
1405  2 this.callbackHandler.handle(cbs);
1406    }
1407    catch (Exception e) {
1408  0 System.err.println(e.getMessage());
1409  0 sawsDebugLog.write(e);
1410    }
1411   
1412  2 return ((SAWSChoiceCallback)this.cbs[0]).getSelectedIndex();
1413    }
1414   
1415    }