View Javadoc

1   /********************************************************************************
2    *InternetCafe is a software solution that helps the management of Cybercafes 
3    * according with the ITALIAN DECREE LAW ON ANTI-TERROR MEASURES, 27 JULY 2005.
4    * Copyright (C) 2006  Guido Angelo Ingenito
5   
6    * This program is free software; you can redistribute it and/or
7    * modify it under the terms of the GNU General Public License
8    * as published by the Free Software Foundation; either version 2
9    * of the License, or (at your option) any later version.
10  
11   * This program is distributed in the hope that it will be useful,
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   * GNU General Public License for more details.
15   * 
16   * You should have received a copy of the GNU General Public License
17   * along with this program; if not, write to the Free Software
18   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19   *******************************************************************************/
20  package base.jdbs.cryptography.asymmetric;
21  
22  import java.io.File;
23  import java.io.FileInputStream;
24  import java.io.FileOutputStream;
25  import java.security.Key;
26  import java.security.KeyStore;
27  import java.security.cert.X509Certificate;
28  import java.util.Enumeration;
29  
30  import org.apache.log4j.Logger;
31  
32  import base.jdbs.cryptography.KeyRing;
33  import base.user.User;
34  
35  public class AsymmetricKeyRing extends KeyRing<KeyPair> {
36  
37  	public static final String KEY_ENTRY = "-keyentry";
38  
39  	public static final String CERTIFICATE_ENTRY = "-certificateentry";
40  
41  	private static final transient Logger logger = Logger
42  			.getLogger(AsymmetricKeyRing.class.getName());
43  
44  	/*** The asymmetric key ring owner.* */
45  	private final User owner;
46  
47  	/***
48  	 * The default constructor.
49  	 */
50  	public AsymmetricKeyRing(User owner) {
51  		this.owner = owner;
52  	}
53  
54  	/***
55  	 * @return Returns the owner.
56  	 */
57  	public User getOwner() {
58  		return owner;
59  	}
60  
61  	/***
62  	 * This method adds a keypair to the collection.
63  	 * 
64  	 * @param keyPair
65  	 *            The keypair to be added.
66  	 */
67  	public void addKeyPair(KeyPair keyPair) {
68  		super.add(keyPair.getId(), keyPair);
69  	}
70  
71  	/***
72  	 * This method removes a keypair from the collection.
73  	 * 
74  	 * @param keyPairId
75  	 *            The keypair identifier associated to the keypair that must be
76  	 *            removed from the collection.
77  	 */
78  	public void removeKeyPair(Integer keyPairId) {
79  		super.remove(keyPairId);
80  	}
81  
82  	/***
83  	 * This method removes all the keypairs contained in the collection.
84  	 */
85  	public void removeAllKeyPair() {
86  		super.removeAll();
87  	}
88  
89  	/***
90  	 * This method retrieves a keypair givind its identifier.
91  	 * 
92  	 * @param keyPairId
93  	 *            The keypair identifier associated to the keypair that must be
94  	 *            retrieved.
95  	 * @return The keypair whose identifier is keyPairId, null if the keyPairId
96  	 *         is not associated to any keypair in the collection.
97  	 */
98  	public KeyPair getKeyPair(Integer keyPairId) {
99  		return super.get(keyPairId);
100 	}
101 
102 	/***
103 	 * This method returns all the keypairs contained in the collection.
104 	 * 
105 	 * @return All the keypairs contained in the collection in array form.
106 	 */
107 	public KeyPair[] getAllKeyPair() {
108 		return super.getAll().toArray(new KeyPair[0]);
109 	}
110 
111 	/***
112 	 * This method computes a new Id for a KeyPair.
113 	 * 
114 	 * @return A new Id for a KeyPair.
115 	 */
116 	protected Integer nextKeyPairId() {
117 		return super.nextElementId();
118 	}
119 
120 	/*
121 	 * (non-Javadoc)
122 	 * 
123 	 * @see base.jdbs.cryptography.KeyRing#store(java.io.File, java.lang.String)
124 	 */
125 	public void store(File location, String password) {
126 		logger.debug("Storing KeyRing to : " + location + " with password: "
127 				+ password);
128 		try {
129 			KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
130 			keyStore.load(null, password.toCharArray());
131 
132 			/*
133 			 * If the keystore already exists on the file system, try to load
134 			 * its content... otherwise create a new one adding fresh data...
135 			 */
136 			if (location.exists()) {
137 				try {
138 					FileInputStream fileInputStream = new FileInputStream(
139 							location);
140 					keyStore.load(fileInputStream, password.toCharArray());
141 					fileInputStream.close();
142 				} catch (Exception ex) {
143 					logger.error(ex.getMessage());
144 					ex.printStackTrace();
145 				}
146 			}
147 
148 			KeyPair[] keyPair = this.getAllKeyPair();
149 			for (int i = 0; i < keyPair.length; i++) {
150 				if (keyStore.containsAlias(keyPair[i].alias() + KEY_ENTRY))
151 					logger.debug("The key store already contains the alias: "
152 							+ keyPair[i].alias() + KEY_ENTRY
153 							+ " it will be overwritten.");
154 				if (keyStore.containsAlias(keyPair[i].alias()
155 						+ CERTIFICATE_ENTRY))
156 					logger.debug("The key store already contains the alias: "
157 							+ keyPair[i].alias() + CERTIFICATE_ENTRY
158 							+ " it will be overwritten.");
159 
160 				keyStore.setKeyEntry(keyPair[i].alias() + KEY_ENTRY, keyPair[i]
161 						.getPrivateKey().getValue(), password.toCharArray(),
162 						new X509Certificate[] { keyPair[i].getCertificate() });
163 				keyStore.setCertificateEntry(keyPair[i].alias()
164 						+ CERTIFICATE_ENTRY, keyPair[i].getCertificate());
165 			}
166 
167 			// Save the new keystore contents
168 			logger.debug("Writing the keystore on file system...");
169 			FileOutputStream out = new FileOutputStream(location);
170 			keyStore.store(out, password.toCharArray());
171 			out.close();
172 			logger.debug("Keystore successfully wrote...");
173 
174 		} catch (Exception ex) {
175 			logger.error(ex.getMessage());
176 			ex.printStackTrace();
177 		}
178 	}
179 
180 	/*
181 	 * (non-Javadoc)
182 	 * 
183 	 * @see base.jdbs.cryptography.KeyRing#retrieve(java.io.File,
184 	 *      java.lang.String)
185 	 */
186 	public KeyStore retrieve(File location, String password) {
187 		KeyStore keyStore = null;
188 		try {
189 			keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
190 			FileInputStream fileInputStream = new FileInputStream(location);
191 			keyStore.load(fileInputStream, password.toCharArray());
192 			fileInputStream.close();
193 
194 			// For each key entry we must retrieve the private key and its
195 			// certificate.
196 			Enumeration aliasEnumerationOnKey = keyStore.aliases();
197 			while (aliasEnumerationOnKey.hasMoreElements()) {
198 				String keyAlias = aliasEnumerationOnKey.nextElement()
199 						.toString();
200 				if (keyStore.isKeyEntry(keyAlias)) {
201 					Key key = keyStore.getKey(keyAlias, password.toCharArray());
202 					String certAlias = keyAlias.replaceAll(KEY_ENTRY,
203 							CERTIFICATE_ENTRY);
204 					if (keyStore.isCertificateEntry(certAlias)) {
205 						X509Certificate certificate = (X509Certificate) keyStore
206 								.getCertificate(certAlias);
207 						logger.debug("This is the certificate: \n"
208 								+ certificate);
209 						base.jdbs.cryptography.asymmetric.PublicKey publicKey = new base.jdbs.cryptography.asymmetric.PublicKey(
210 								certificate.getPublicKey());
211 						logger.debug("This is the publicKey: \n"
212 								+ publicKey.getValue());
213 						base.jdbs.cryptography.asymmetric.PrivateKey privateKey = new base.jdbs.cryptography.asymmetric.PrivateKey(
214 								(java.security.PrivateKey) key);
215 						logger.debug("This is the privateKey: \n"
216 								+ privateKey.getValue());
217 						this.addKeyPair(new KeyPair(this.nextKeyPairId(), this
218 								.getOwner().getNickname()
219 								+ "-KeyPair", publicKey, privateKey,
220 								certificate));
221 					} else
222 						logger.error(certAlias
223 								+ " isn't a certificate entry!!!");
224 
225 				}
226 			}
227 
228 		} catch (Exception ex) {
229 			logger.error(ex.getMessage());
230 			ex.printStackTrace();
231 		}
232 		return keyStore;
233 	}
234 }