KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ejbca > samples > HttpGetCert


1 /*************************************************************************
2  * *
3  * EJBCA: The OpenSource Certificate Authority *
4  * *
5  * This software is free software; you can redistribute it and/or *
6  * modify it under the terms of the GNU Lesser General Public *
7  * License as published by the Free Software Foundation; either *
8  * version 2.1 of the License, or any later version. *
9  * *
10  * See terms of license at gnu.org. *
11  * *
12  *************************************************************************/

13  
14 package org.ejbca.samples;
15
16 import java.io.BufferedReader JavaDoc;
17 import java.io.ByteArrayOutputStream JavaDoc;
18 import java.io.InputStreamReader JavaDoc;
19 import java.io.PrintWriter JavaDoc;
20 import java.net.HttpURLConnection JavaDoc;
21 import java.net.URL JavaDoc;
22 import java.net.URLConnection JavaDoc;
23 import java.net.URLEncoder JavaDoc;
24 import java.security.KeyPair JavaDoc;
25
26 import org.apache.log4j.BasicConfigurator;
27 import org.apache.log4j.Logger;
28 import org.bouncycastle.asn1.DEROutputStream;
29 import org.bouncycastle.jce.PKCS10CertificationRequest;
30 import org.ejbca.core.model.ca.catoken.CATokenConstants;
31 import org.ejbca.util.Base64;
32 import org.ejbca.util.CertTools;
33 import org.ejbca.util.KeyTools;
34
35
36
37 /**
38  * Example how a certificate can be fetched programmatically using HTTP/S. The sample generates a
39  * certificate request and uses POST to the same servlet as used from a browser through
40  * http://127.0.0.1:8080/ejbca/publicweb/apply/apply_man.jsp.
41  * The servlet url used in the example is
42  * http://127.0.0.1:8080/ejbca/publicweb/apply/certreq.
43  * The certificate reply containing a PEM-formatted certificate is printed to the screen.
44  *
45  * NOTE: Support for SSL has been commented out in this sample, since it requires JSSE. This sample
46  * class generates a PKCS10 request and POSTs to the CAs web interface. The reply is received and
47  * printed to stdout. Takes arguments:
48  *
49  * <ul>
50  * <li>
51  * requesturl - URL to the CA web (servlet where requests are POSTed),
52  * http://127.0.0.1/apply/apply_man.jsp.
53  * </li>
54  * <li>
55  * username - username of a user registered with the CA with status NEW.
56  * </li>
57  * <li>
58  * password - password for the above user.
59  * </li>
60  * </ul>
61  *
62  * @version $Id: HttpGetCert.java,v 1.2 2006/10/31 08:21:29 anatom Exp $
63  */

64 public class HttpGetCert {
65     private static Logger log = Logger.getLogger(HttpGetCert.class);
66
67     /**
68      * Constructor
69      */

70     public HttpGetCert() {
71         log.debug(">HttpGetCert:");
72
73         // Use for SSL connections
74
/*
75         System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");
76         java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
77         */

78         log.debug("<HttpGetCert:");
79     }
80
81     // HttpGetCert
82

83     /**
84      * Sets the CA certificate used to verify the web server's certificate. We only support a
85      * single self-signed CA certificate here.
86      *
87      * @param url servercertificate
88      *
89      * @return DOCUMENT ME!
90      *
91      * @exception java.security.cert.CertificateException if the certificate is not correct.
92      * @throws IllegalArgumentException if webcert is not a self-signed certificate
93      */

94
95     // Use for SSL connections
96

97     /*
98     public void setSSLTrustedServerCert(byte[] cert) throws java.security.cert.CertificateException {
99     log.debug(">setSSLTrustedServerCert:");
100     CertificateFactory cf = CertTools.getCertificateFactory();
101     webcert = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(cert));
102     if ( CertTools.isSelfSigned( webcert ) )
103         throw new IllegalArgumentException("Webcert certificate is not self signed (not a root CA certificate).");
104     log.debug("<setSSLTrustedServerCert:");
105
106     } // setSSLTrustedServerCert
107     */

108
109     /**
110      * Creates a SSLSocketFactory to communicate with the server using HTTPS.
111      *
112      * @param url DOCUMENT ME!
113      *
114      * @return DOCUMENT ME!
115      *
116      * @throws IllegalArgumentException if webcert is not set.
117      * @throws Exception error in setting up SSLContext.
118      */

119
120     // Use for SSL connections
121

122     /*
123     private SSLSocketFactory getSSLFactory() throws IllegalArgumentException, Exception {
124         log.debug( ">getSSLFactory" );
125         SSLContext ctx = SSLContext.getInstance( "SSL" );
126         KeyManagerFactory kmf = KeyManagerFactory.getInstance( "SunX509" );
127         String proxyHost = null;
128         String proxyPort = null;
129
130         // if we are behind a proxy, there must be set
131         if (proxyHost != null)
132             System.setProperty("https.proxyHost", proxyHost);
133         if (proxyPort != null)
134             System.setProperty("https.proxyPort", proxyPort);
135
136         if (webcert == null)
137             throw new IllegalArgumentException("Server certificate must be set for SSL communication");
138
139         // If we must use client certificates here, we should read some certs and keys and create a keystore to put in the KeyManagerFactory
140
141         // Make a truststore to verify the server
142         KeyStore trustks = KeyStore.getInstance( "jks" );
143         trustks.load( null, new String("foo123").toCharArray() );
144         trustks.setCertificateEntry( "trustedRootCA", webcert);
145         TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
146         tmf.init( trustks );
147
148         ctx.init( null, tmf.getTrustManagers(), null );
149
150         log.debug( "<getSSLFactory" );
151         return ctx.getSocketFactory();
152     }
153     */

154
155     /**
156      * Creates a URLConnection either HTTP or HTTPS.
157      *
158      * @param url the URL (http:// or https://
159      *
160      * @return URLConnection
161      */

162     private URLConnection JavaDoc getUrlConnection(URL JavaDoc url) throws Exception JavaDoc {
163         URLConnection JavaDoc con = url.openConnection();
164
165         // Use for SSL connections
166

167         /*
168         if( con instanceof HttpsURLConnection ) {
169             HttpsURLConnection httpscon = (HttpsURLConnection) con;
170             httpscon.setSSLSocketFactory( getSSLFactory() );
171         }
172         */

173         return con;
174     }
175
176     /**
177      * Sends a certificate request (PKCS10) to the CA and receives the reply.
178      *
179      * @param requestUrl DOCUMENT ME!
180      * @param request Base64 encoded PKCS10-request (PEM-format)
181      * @param username username
182      * @param password password
183      *
184      * @exception IllegalArgumentException if requesturl is not a vlid HTTP or HTTPS url.
185      * @exception Exception if the trusted webcert is not a correct certificate.
186      * @exception Exception if we get back a HTTP response code != 200 from the CA.
187      * @exception Exception if the reply is not a correct certificate.
188      */

189     public void sendHttpReq(String JavaDoc requestUrl, String JavaDoc request, String JavaDoc username, String JavaDoc password)
190         throws Exception JavaDoc {
191         log.debug(">sendHttpReq: request=" + request.toString() + ", username=" + username +
192             ", password=" + password);
193
194         if (requestUrl == null) {
195             throw new IllegalArgumentException JavaDoc("requesturl can not be null.");
196         }
197
198         log.debug("Sending request to: " + requestUrl);
199
200         URL JavaDoc url = new URL JavaDoc(requestUrl);
201         HttpURLConnection JavaDoc con = (HttpURLConnection JavaDoc) getUrlConnection(url);
202
203         // we are going to do a POST
204
con.setDoOutput(true);
205         con.setRequestMethod("POST");
206
207         // POST it
208
PrintWriter JavaDoc out = new PrintWriter JavaDoc(con.getOutputStream());
209         out.println("pkcs10req=" + URLEncoder.encode(request,"UTF-8") + "&user=" +
210             URLEncoder.encode(username,"UTF-8") + "&password=" + URLEncoder.encode(password,"UTF-8") +
211             "&submit=Submit+Query");
212         out.close();
213
214         // Read the reqponse
215
BufferedReader JavaDoc in = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(con.getInputStream()));
216         String JavaDoc inputLine;
217
218         while ((inputLine = in.readLine()) != null) {
219             System.out.println(inputLine);
220         }
221
222         if (con.getResponseCode() == 200) {
223             log.debug("Received certificate reply.");
224         } else {
225             throw new Exception JavaDoc("Error sending PKCS10-request.");
226         }
227
228         // We are done, disconnect
229
con.disconnect();
230
231         log.debug("<sendHttpReq:");
232     }
233
234     // sendHttpReq
235

236     /**
237      * DOCUMENT ME!
238      *
239      * @param args DOCUMENT ME!
240      *
241      * @throws Exception DOCUMENT ME!
242      */

243     public static void main(String JavaDoc[] args) throws Exception JavaDoc {
244         //Configure Log4j
245
BasicConfigurator.configure();
246
247         // Install BouncyCastle provider
248
CertTools.installBCProvider();
249
250         // Generate keys (512 bit for sample purposes)
251
System.out.print("Generating 512 bit RSA keys.");
252
253         KeyPair JavaDoc rsaKeys = KeyTools.genKeys("512", CATokenConstants.KEYALGORITHM_RSA);
254         System.out.println("Keys generated.");
255
256         // Generate PKCS10 certificate request
257
PKCS10CertificationRequest req = new PKCS10CertificationRequest("SHA1WithRSA",
258                 CertTools.stringToBcX509Name("C=SE,O=AnaTom,CN=HttpTest"), rsaKeys.getPublic(),
259                 null, rsaKeys.getPrivate());
260         ByteArrayOutputStream JavaDoc bOut = new ByteArrayOutputStream JavaDoc();
261         DEROutputStream dOut = new DEROutputStream(bOut);
262         dOut.writeObject(req);
263         dOut.close();
264
265         ByteArrayOutputStream JavaDoc bos1 = new ByteArrayOutputStream JavaDoc();
266         bos1.write("-----BEGIN CERTIFICATE REQUEST-----\n".getBytes());
267         bos1.write(Base64.encode(bOut.toByteArray()));
268         bos1.write("\n-----END CERTIFICATE REQUEST-----\n".getBytes());
269         bos1.close();
270         System.out.println("CertificationRequest generated:");
271         System.out.println(new String JavaDoc(bos1.toByteArray()));
272
273         // Now send the request
274
System.out.println("Trying to send request...");
275
276         HttpGetCert getter = new HttpGetCert();
277         getter.sendHttpReq("http://127.0.0.1:8080/apply/certreq", new String JavaDoc(bos1.toByteArray()),
278             "foo", "foo123");
279     }
280 }
281
282
283 // class CertRequest
284
Popular Tags