View Javadoc

1   package org.eparapher.core.crypto.keystore;
2   
3   import java.io.File;
4   import java.io.FileInputStream;
5   import java.io.FileNotFoundException;
6   import java.io.FileOutputStream;
7   import java.io.IOException;
8   import java.security.KeyStore;
9   import java.security.KeyStoreException;
10  import java.security.NoSuchAlgorithmException;
11  import java.security.NoSuchProviderException;
12  import java.security.cert.CertificateException;
13  
14  import org.apache.log4j.Logger;
15  import org.eparapher.core.EParapherManager;
16  import org.eparapher.core.crypto.EPKeystoreManager;
17  
18  
19  public class FileKeystore extends GenericKeystore implements ITrustStore{
20  
21  	private static Logger log = Logger.getLogger(FileKeystore.class);
22  	
23  	private String keystoreFilePath;
24  	private String keystoreType;
25  	private String keystorePassword = null;
26  	
27  	public FileKeystore(String keystore_type, String keystore_file) {
28  		super();
29  		ks = null;
30  		keystoreType = keystore_type;
31  		keystoreFilePath = keystore_file;
32  	}
33  
34  	public boolean loadKeyStore()  {
35  
36  		//Check if already loaded
37  		if (this.isKeystoreLoaded())
38  			return true;
39  		
40  		log.info("Loading user keystore File : " + keystoreFilePath);
41  
42  		//check if Keystore file exists
43  		if ( !this.exists() ) {
44  			if (!this.initialize())
45  				return false;
46  		} else {
47  			// Launch Wizard to ask user Passphrase to open keystore
48  			if ( !callGUIForPassphrase(false) )
49  				return false;
50  			
51  			this.loadedKeystore = true;
52  			
53  			selectAlias();
54  		}
55  		return true;
56  	}
57  
58  	private boolean createNewKeystore() {
59  		log.info("Creating  " + keystoreFilePath + " software keystore");
60  		
61  		try {
62  			if (keystoreType.equals(EPKeystoreManager.PKCS12_CONFIGNAME))
63  				ks = KeyStore.getInstance( keystoreType, "BC" );
64  			else 
65  				ks = KeyStore.getInstance( keystoreType );
66  			
67  			//Prompt user for password
68  			if (keystorePassword==null || keystorePassword.equals(""))
69  				keystorePassword = callGUIForNewPassphrase(false);
70  			
71  			// exit if keystorePassword is null
72  			if (keystorePassword==null)
73  				return false;
74  			
75  			//Initialize Keystore
76  			ks.load(null,keystorePassword.toCharArray());
77  			
78  			if (!keystoreFilePath.equals(EParapherManager.getInstance().getSettings().getFileKeystorePath())) {
79  				//Create a new Certificate
80  				if ( EParapherManager.getInstance().getUI().askUserNewCertificate() )
81  					saveKeyStore();
82  				else
83  					log.info("New Certificate wizard cancelled");
84  			}
85  			this.loadedKeystore = true;
86  		} catch (KeyStoreException e) {
87  			log.error(""+e.getLocalizedMessage(),e);
88  		} catch (NoSuchAlgorithmException e) {
89  			log.error(""+e.getLocalizedMessage(),e);
90  		} catch (CertificateException e) {
91  			log.error(""+e.getLocalizedMessage(),e);
92  		} catch (IOException e) {
93  			log.error(""+e.getLocalizedMessage(),e);
94  		} catch (NoSuchProviderException e) {
95  			log.error(""+e.getLocalizedMessage(),e);
96  		}
97  		return this.loadedKeystore;
98  	}
99  
100 	public boolean loadKeyStore(String passphrase) {
101 		try {
102 
103 			if (keystoreType.toUpperCase().equals(EPKeystoreManager.PKCS12_CONFIGNAME))
104 				ks = KeyStore.getInstance( keystoreType, "BC" );
105 			else
106 				ks = KeyStore.getInstance( keystoreType );
107 
108 			if (passphrase == null)
109 				return false;
110 			keystorePassword = passphrase;
111 			
112 			FileInputStream fis = new FileInputStream(keystoreFilePath);
113 
114 			ks.load(fis, keystorePassword.toCharArray());
115 
116 			log.info("User keystore Loaded");
117 			return true;
118 		}
119 		catch (FileNotFoundException fnfe) {
120 			log.debug("File " + keystoreFilePath + " not found.");
121 		}
122 		catch (IOException e) {
123 			log.debug("Cannot Open Keystore file " + keystoreFilePath + " with user's secret. ("  + e.getLocalizedMessage() + ")");
124 		}
125 		catch (NoSuchAlgorithmException e) {
126 			log.debug("Keystore file " + keystoreFilePath + " not opened : "  + e.getLocalizedMessage(),e);
127 		}
128 		catch (CertificateException e) {
129 			log.debug("Keystore file " + keystoreFilePath + " not opened : "  + e.getLocalizedMessage(),e);
130 		}
131 		catch (KeyStoreException e) {
132 			log.debug("Keystore file " + keystoreFilePath + " not opened : "  + e.getLocalizedMessage(),e);
133 			//log.error("Error: " + keystoreFilePath + " file is invalid or passphrase is incorrect");
134 		} catch (NoSuchProviderException e) {
135 			log.debug("Keystore Provider BouncyCastle not founded",e);
136 			}
137 		/*
138 		catch (NoSuchProviderException e) {
139 			log.debug("Keystore file " + keystoreFilePath + " not opened : "  + e.getLocalizedMessage());
140 			//log.error(""+e.getLocalizedMessage(),e);
141 		}*/
142 		return false;
143 	}
144 	
145 	/**
146 	 * Launch Wizard to ask user Password to open keystore
147 	 * @param isForPK true if asking passphrase for Private Key, false for opening Keystore
148 	 * @return
149 	 */
150 	private boolean callGUIForPassphrase(boolean isForPK) {
151 		
152 		String passphrase = EParapherManager.getInstance().getUI().askUserKeystoreSecret(false, isForPK, getDefaultAlias() );
153 		return passphrase != null;
154 	}
155 
156 	private String callGUIForNewPassphrase(boolean isForPK) {
157 		return EParapherManager.getInstance().getUI().askUserKeystoreSecret(true, isForPK, getDefaultAlias() );
158 	}
159 	
160 	public String getKeystoreFileName() {
161 		return keystoreFilePath;
162 	}
163 	public void setKeystoreFileName(String fileName) {
164 		keystoreFilePath = fileName;
165 	}
166 
167 	public boolean loadPrivateKey() {
168 		if (!this.isKeystoreLoaded())
169 			if (!loadKeyStore())
170 				return false;
171 		// Launch Wizard to ask user the Passphrase to access the Private Key alias
172 		if (!selectAlias())
173 			return false;
174 		
175 		//No Private Key password for PKCS12 File
176 		if (keystoreType.toUpperCase().equals("PKCS12")) {
177 			loadPrivateKey("");
178 			return true;
179 		} else
180 			return callGUIForPassphrase(true);
181 	}
182 
183 	public boolean loadTrustStore() {
184 		
185 		//Check if already loaded
186 		if (this.isKeystoreLoaded())
187 			return true;
188 		
189 		//Check if file exists
190 		if (!this.exists())
191 			return false;
192 		// Load Keystore
193 		try {
194 			if (keystoreType.toUpperCase().equals("PKCS12"))
195 				ks = KeyStore.getInstance( keystoreType, "BC" );
196 			else
197 				ks = KeyStore.getInstance( keystoreType );
198 
199 			keystorePassword = "changeit";
200 			
201 			FileInputStream fis = new FileInputStream(keystoreFilePath);
202 
203 			ks.load(fis, keystorePassword.toCharArray());
204 			
205 			this.loadedKeystore = true;
206 
207 			return true;
208 		} catch (FileNotFoundException fnfe) {
209 			log.debug("File " + keystoreFilePath + " not found.");
210 		} catch (IOException e) {
211 			log.debug("Keystore file " + keystoreFilePath + " not opened : "  + e.getLocalizedMessage());
212 		} catch (NoSuchAlgorithmException e) {
213 			log.debug("Keystore file " + keystoreFilePath + " not opened : "  + e.getLocalizedMessage());
214 		} catch (CertificateException e) {
215 			log.debug("Keystore file " + keystoreFilePath + " not opened : "  + e.getLocalizedMessage());
216 		} catch (KeyStoreException e) {
217 			log.debug("Keystore file " + keystoreFilePath + " not opened : "  + e.getLocalizedMessage());
218 		} catch (NoSuchProviderException e) {
219 			log.debug("Cannot open keystore file " + keystoreFilePath + ", security provider is missing : "  + e.getLocalizedMessage());
220 		}
221 		
222 		return false;
223 	}
224 
225 	public boolean saveTrustStore() {
226 		return saveKeyStore();
227 	}
228 
229 	public boolean saveKeyStore() {
230 		if (this.loadedKeystore) {
231 			FileOutputStream fos;
232 			try {
233 				File f = new File(keystoreFilePath);
234 				if (!f.exists()) {
235 					log.info("Cannot find Keystore file.");
236 					log.info("AbsolutePath : "+f.getAbsolutePath());
237 					log.info("Canonical    : "+f.getCanonicalPath());
238 				}
239 				fos = new FileOutputStream(f.getCanonicalPath());
240 				log.info("Saving file Keystore (" + keystoreType + ") to " + f.getCanonicalPath());
241 				ks.store(fos, keystorePassword.toCharArray());
242 				return true;
243 			} catch (FileNotFoundException e) {
244 				log.error("File " + keystoreFilePath + " not found.");
245 			} catch (KeyStoreException e) {
246 				log.error("Keystore file " + keystoreFilePath + " not opened : "  + e.getLocalizedMessage());
247 			} catch (NoSuchAlgorithmException e) {
248 				log.error(e.getLocalizedMessage(),e);
249 			} catch (CertificateException e) {
250 				log.error(e.getLocalizedMessage(),e);
251 			} catch (IOException e) {
252 				log.error(e.getLocalizedMessage(),e);
253 			}
254 		}
255 		return false;
256 	}
257 
258 	public char[] getKSPassword() {
259 		return this.keystorePassword.toCharArray();
260 	}
261 	
262 	public void setKSPassword(String pwd) {
263 		this.keystorePassword = pwd;
264 	}
265 
266 	/**
267 	 * Check if Keystore file exists
268 	 */
269 	public boolean exists() {
270 		File myFile = new File(keystoreFilePath);
271 		if ( !myFile.exists() ) {
272 			log.warn("Warning: File " + keystoreFilePath + " not found.");
273 			return false;
274 		}
275 		if (  !myFile.isFile() ) {
276 			log.warn("Warning: " + keystoreFilePath + " is not a file.");
277 			return false;
278 		}
279 		if ( !myFile.canRead() ) {
280 			log.warn("Warning: Cannot read file " + keystoreFilePath );
281 			return false;
282 		}
283 		return true;
284 	}
285 	public boolean initialize() {
286 		String msg = keystoreType + " file not found : \r\n" + keystoreFilePath + "\r\n\r\n Choose OK to create a new Keystore File and a new certificate\r\n Otherwise, press CANCEL to choose another file and/or keystore type.";
287 		if (EParapherManager.getInstance().getUI().askUserYesNo(msg)) {
288 			if (createNewKeystore()) {
289 				if (newcertificate()) {
290 					return saveKeyStore();
291 				}
292 			}
293 			return false;
294 		} else 
295 			EParapherManager.getInstance().getUI().showKeystoreSettings();
296 		
297 		return true;
298 	}
299 	
300 	public static String getFileKeystoreType() {
301 		if ( EPKeystoreManager.isBCUsed() )
302 			return EPKeystoreManager.BC_CONFIGNAME;
303 		if ( EPKeystoreManager.isJCEKSUsed() )
304 			return EPKeystoreManager.JCEKS_CONFIGNAME;
305 		if ( EPKeystoreManager.isJKSUsed() )
306 			return EPKeystoreManager.JKS_CONFIGNAME;
307 		if ( EPKeystoreManager.isPKCS12Used() )
308 			return EPKeystoreManager.PKCS12_CONFIGNAME;
309 		if ( EPKeystoreManager.isUBERUsed() )
310 			return EPKeystoreManager.UBER_CONFIGNAME;
311 		if ( EPKeystoreManager.isCMSKSUsed() )
312 			return EPKeystoreManager.KDB_CONFIGNAME;
313 		return "";
314 	}
315 }