View Javadoc

1   /*
2   jGuard is a security framework based on top of jaas (java authentication and authorization security).
3   it is written for web applications, to resolve simply, access control problems.
4   
5   http://sourceforge.net/projects/jguard/
6   
7   Copyright (C) 2004  Charles GAY
8   
9   This library is free software; you can redistribute it and/or
10  modify it under the terms of the GNU Lesser General Public
11  License as published by the Free Software Foundation; either
12  version 2.1 of the License, or (at your option) any later version.
13  
14  This library is distributed in the hope that it will be useful,
15  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  Lesser General Public License for more details.
18  
19  You should have received a copy of the GNU Lesser General Public
20  License along with this library; if not, write to the Free Software
21  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  
23  
24  jGuard project home page:
25  http://sourceforge.net/projects/jguard/
26  
27  */
28  package net.sf.jguard.ext.authentication.certificates;
29  
30  import java.io.File;
31  import java.io.FileInputStream;
32  import java.io.FileNotFoundException;
33  import java.io.IOException;
34  import java.security.KeyStore;
35  import java.security.KeyStoreException;
36  import java.security.NoSuchAlgorithmException;
37  import java.security.cert.CertificateException;
38  import java.security.cert.CertificateFactory;
39  import java.security.cert.TrustAnchor;
40  import java.security.cert.X509CRL;
41  import java.security.cert.X509Certificate;
42  import java.util.Arrays;
43  import java.util.HashSet;
44  import java.util.Iterator;
45  import java.util.List;
46  import java.util.Set;
47  import org.slf4j.Logger;
48  import org.slf4j.LoggerFactory;
49  
50  /**
51   * Utility class to handle X509 certificates.
52   *
53   * @author <a href="mailto:slebettre@gmail.com">Simon Lebettre</a>
54   * @author <a href="mailto:diabolo512@users.sourceforge.net">Charles Gay</a>
55   */
56  public class CertUtils {
57  
58  	private static final String X509 = "X509";
59  	/** Logger for this class */
60  	private static final Logger logger = LoggerFactory.getLogger(CertUtils.class.getName());
61  
62  	/**
63       * Read a certificate from the specified filepath.
64       * @param path
65       * @return X509Certificate
66       */
67      public static X509Certificate getCertFromFile(String path) {
68          X509Certificate cert = null;
69  
70              File certFile = new File(path);
71              if (!certFile.canRead()){
72  					logger.error(" File " + certFile.toString() +" is unreadable");
73  					return null;
74              }
75              FileInputStream fis = null;
76  			try {
77  				fis = new FileInputStream(path);
78  			} catch (FileNotFoundException e) {
79  				logger.error( "", e);
80  				return null;
81  
82  			}
83              CertificateFactory cf;
84  			try {
85  				cf = CertificateFactory.getInstance(CertUtils.X509);
86  				cert = (X509Certificate)cf.generateCertificate(fis);
87  			} catch (CertificateException e) {
88  				logger.error( "", e);
89  				return null;
90  			}finally{
91  				try {
92  					fis.close();
93  				} catch (IOException e) {
94  					logger.error( "", e);
95  				}
96  			}
97  
98          return cert;
99      }
100 
101 	/**
102 	 * return all the certificates contained in the directory path.
103 	 * @param directoryPath
104 	 * @return certificates Set, an empty Set if the directoryPath is null
105 	 */
106 	public static Set getCertsFromDirectory(String directoryPath){
107 		Set certsSet = new HashSet();
108 		if(directoryPath==null){
109 			return certsSet;
110 		}
111 	    File file = new File(directoryPath);
112 		List filesAndDirectories =Arrays.asList(file.listFiles());
113 		Iterator it = filesAndDirectories.iterator();
114 
115 		while(it.hasNext()){
116 			File tempFile = (File)it.next();
117 			if(tempFile.isFile()){
118                 certsSet.add(getCertFromFile(tempFile.getPath()));
119 			}
120 		}
121 
122 		return certsSet;
123 	}
124 
125 	/**
126 	 * return a Set of TrustAnchors (without nameConstraints)
127 	 * which comes from a directory path.
128 	 * @param directoryPath
129 	 * @return TrustAnchor Set
130 	 */
131 	public static Set getTrustedAnchorsFromDirectory(String directoryPath){
132 		Set trustedAnchors = new HashSet();
133 		Set certs = getCertsFromDirectory(directoryPath);
134 		Iterator itCerts = certs.iterator();
135 		while(itCerts.hasNext()){
136 			X509Certificate cert = (X509Certificate)itCerts.next();
137 			TrustAnchor trustAnchor = new TrustAnchor(cert,null);
138 			trustedAnchors.add(trustAnchor);
139 		}
140 		return trustedAnchors;
141 	}
142 
143 	/**
144 	 * return a Set of TrustAnchors (without nameConstraints)
145 	 * which comes from a directory path.
146 	 * @param directoryPath
147 	 * @param nameConstraints constraints applied to all the TrustAnchor
148 	 * @return TrustAnchor Set
149 	 */
150 	public static Set getTrustedAnchorsFromDirectory(String directoryPath,byte[] nameConstraints){
151 		Set trustedAnchors = new HashSet();
152 		Set certs = getCertsFromDirectory(directoryPath);
153 		Iterator itCerts = certs.iterator();
154 		while(itCerts.hasNext()){
155 			X509Certificate cert = (X509Certificate)itCerts.next();
156 			TrustAnchor trustAnchor = new TrustAnchor(cert,nameConstraints);
157 			trustedAnchors.add(trustAnchor);
158 		}
159 		return trustedAnchors;
160 	}
161 
162 	/**
163 	 * output the CRL content.
164 	 * @param crl to inspect
165 	 */
166 	private void inspectCRL(X509CRL crl) {
167             if(logger.isDebugEnabled()){
168                 logger.debug("crl="+crl.toString());
169                 logger.debug("crlType="+crl.getType());
170                 logger.debug("crl next update Date="+crl.getNextUpdate());
171                 logger.debug("crl issuer DN="+crl.getIssuerDN().getName());
172                 logger.debug("crl signature algorithm name ="+crl.getSigAlgName());
173                 logger.debug("crl signature algorithm oid ="+crl.getSigAlgOID());
174                 logger.debug("crl version ="+crl.getVersion());
175                 logger.debug("crl update Date ="+crl.getThisUpdate());
176             }
177 			Set revokedCertificates = crl.getRevokedCertificates();
178 			Iterator itRevokedCerts = revokedCertificates.iterator();
179 			while(itRevokedCerts.hasNext()){
180 			     X509Certificate certificate = (X509Certificate)itRevokedCerts.next();
181 				 logger.debug(certificate.toString());
182 			}
183 			Set criticalExtensions = crl.getCriticalExtensionOIDs();
184 			Iterator itCritExtensions = criticalExtensions.iterator();
185 			while(itCritExtensions.hasNext()){
186 				String oid = (String)itCritExtensions.next();
187 				 logger.debug(" critical extension = "+oid);
188 			}
189 			Set nonCriticalExtensions = crl.getNonCriticalExtensionOIDs();
190 			Iterator itNonCritExtensions = nonCriticalExtensions.iterator();
191 			while(itNonCritExtensions.hasNext()){
192 				String oid = (String)itNonCritExtensions.next();
193 				 logger.debug(" non critical extension = "+oid);
194 			}
195 
196 	}
197 	
198 	public static KeyStore getKeyStore(String filePath,String keyStorePassword,String keyStoreType) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException{
199 		FileInputStream fis = new FileInputStream(filePath);
200 		KeyStore keystore = KeyStore.getInstance(keyStoreType);
201 	    keystore.load(fis,keyStorePassword.toCharArray());
202 		return keystore;
203 	}
204 
205 }