KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > jcetaglib > lib > Signatures


1 /*
2   Name: Signatures.java
3   Licensing: LGPL
4
5   API: Sun (http://java.sun.com) JCE 1.2.2 API (cleanroom implementation by Bouncy Castle)
6   Provider: Bouncy Castle (http://www.bouncycastle.org)
7
8   Disclaimer:
9
10   COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY OF ANY KIND,
11   EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE
12   IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE
13   RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE IS WITH YOU. SHOULD ANY COVERED CODE
14   PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR)
15   ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY
16   CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED
17   HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
18
19   (C) Copyright 2003 Gert Van Ham
20 */

21
22 package net.sourceforge.jcetaglib.lib;
23
24 import net.sourceforge.jcetaglib.exceptions.CryptoException;
25 import org.bouncycastle.jce.provider.BouncyCastleProvider;
26 import org.bouncycastle.util.encoders.Base64;
27
28 import java.io.*;
29 import java.security.PrivateKey JavaDoc;
30 import java.security.PublicKey JavaDoc;
31 import java.security.Security JavaDoc;
32 import java.security.Signature JavaDoc;
33
34 /**
35  * Create and verify SIGs (Signatures) with the BouncyCastle JCE provider
36  *
37  * @author Gert Van Ham
38  * @author hamgert@users.sourceforge.net
39  * @author http://jcetaglib.sourceforge.net
40  * @version $Id: Signatures.java,v 1.3 2004/04/15 07:28:25 hamgert Exp $
41  */

42 public class Signatures {
43     // buffersizes in bytes
44
private static int BUFFERSIZE_TEXT = 64;
45     private static int BUFFERSIZE_FILE = 8192;
46
47     /**
48      * Generates and returns a SIG (Signature) from a text
49      *
50      * @param text text to create SIG from
51      * @param signingKey the signing key
52      * @param signame Signature algorithm (e.g. RIPEMD160WithRSA/ISO9796-2)
53      * @return SIG in BASE64 format
54      * @throws CryptoException for all encryption errors
55      */

56     public static StringBuffer JavaDoc generateSIG(StringBuffer JavaDoc text
57                                            , PrivateKey JavaDoc signingKey
58                                            , String JavaDoc signame)
59             throws CryptoException {
60
61         ByteArrayOutputStream bao = null;
62         DataOutputStream dao = null;
63
64         try {
65             bao = new ByteArrayOutputStream();
66             dao = new DataOutputStream(bao);
67
68             // Create MAC
69
generateSIG(new ByteArrayInputStream(text.toString().getBytes()), dao, signingKey, signame, BUFFERSIZE_TEXT);
70
71             return new StringBuffer JavaDoc(new String JavaDoc(Base64.encode(bao.toByteArray())));
72         } catch (IOException ioe) {
73             ioe.printStackTrace();
74             throw new CryptoException(ioe.getMessage());
75         } finally {
76             if (dao != null) {
77                 // close outputstream
78
try {
79                     dao.close();
80                 } catch (IOException e) {
81                     ;
82                 }
83             }
84         }
85     }
86
87     /**
88      * Generates and returns a SIG (Signature) from a file
89      *
90      * @param file file to create SIG from
91      * @param signingKey the signing key
92      * @param signame Signature algorithm (e.g. RIPEMD160WithRSA/ISO9796-2)
93      * @return SIG in BASE64 format
94      * @throws CryptoException for all encryption errors
95      */

96     public static StringBuffer JavaDoc generateFileSIG(String JavaDoc file
97                                                , PrivateKey JavaDoc signingKey
98                                                , String JavaDoc signame)
99             throws CryptoException {
100
101         FileInputStream fis = null;
102         ByteArrayOutputStream bao = null;
103         DataOutputStream dao = null;
104
105         try {
106             fis = new FileInputStream(file);
107             bao = new ByteArrayOutputStream();
108             dao = new DataOutputStream(bao);
109
110             // generate mac
111
generateSIG(fis, dao, signingKey, signame, BUFFERSIZE_FILE);
112
113             return new StringBuffer JavaDoc(new String JavaDoc(Base64.encode(bao.toByteArray())));
114
115         } catch (IOException ioe) {
116             ioe.printStackTrace();
117             throw new CryptoException(ioe.getMessage());
118         } finally {
119             if (dao != null) {
120                 // close outputstream
121
try {
122                     dao.close();
123                 } catch (IOException e) {
124                     ;
125                 }
126             }
127             if (fis != null) {
128                 // close outputstream
129
try {
130                     fis.close();
131                 } catch (IOException e) {
132                     ;
133                 }
134             }
135         }
136     }
137
138     /**
139      * Generates and returns a SIG (Signature) from any inputstream
140      *
141      * @param is inputstream to generate SIG from
142      * @param daos returns SIG code outputstream
143      * @param signingKey the signing key
144      * @param signame Signature algorithm (e.g. RIPEMD160WithRSA/ISO9796-2)
145      * @throws IOException I/O errors
146      * @throws CryptoException for all encryption errors
147      **/

148     public static void generateSIG(InputStream is
149                                    , DataOutputStream daos
150                                    , PrivateKey JavaDoc signingKey
151                                    , String JavaDoc signame
152                                    , int bufferlength)
153             throws CryptoException, IOException {
154
155         Signature JavaDoc sig = null;
156
157         try {
158             // Add Bouncy Castle provider
159
Security.addProvider(new BouncyCastleProvider());
160
161             sig = Signature.getInstance(signame, "BC");
162             sig.initSign(signingKey);
163
164             byte[] buffer = new byte[bufferlength];
165             int length = 0;
166
167             // Read bytes into buffer
168
while ((length = is.read(buffer)) != -1) {
169                 sig.update(buffer, 0, length);
170             }
171
172             byte[] result = sig.sign();
173             daos.write(result);
174         } catch (IOException ioe) {
175             ioe.printStackTrace();
176             throw new IOException(ioe.getMessage());
177         } catch (Exception JavaDoc ex) {
178             ex.printStackTrace();
179             throw new CryptoException(ex.getMessage());
180         }
181     }
182
183     /**
184      * Verifies a signature from a text
185      *
186      * @param text text to verify
187      * @param signature the signature (in BASE64 format)
188      * @param verifyKey the verification key
189      * @param signame Signature algorithm (e.g. RIPEMD160WithRSA/ISO9796-2)
190      * @return true (verified) or false (invalid)
191      * @throws CryptoException for encryption errors
192      */

193     public static boolean verifySIG(StringBuffer JavaDoc text
194                                     , StringBuffer JavaDoc signature
195                                     , PublicKey JavaDoc verifyKey
196                                     , String JavaDoc signame)
197             throws CryptoException {
198
199         try {
200             // Verify SIG
201
return verifySIG(new ByteArrayInputStream(text.toString().getBytes()), signature, verifyKey, signame, BUFFERSIZE_TEXT);
202
203         } catch (IOException ioe) {
204             ioe.printStackTrace();
205             throw new CryptoException(ioe.getMessage());
206         }
207     }
208
209     /**
210      * Verifies a signature from a file
211      *
212      * @param file file to verify
213      * @param signature the signature (in BASE64 format)
214      * @param verifyKey the verification key
215      * @param signame Signature algorithm (e.g. RIPEMD160WithRSA/ISO9796-2)
216      * @return true (verified) or false (invalid)
217      * @throws CryptoException for encryption errors
218      */

219     public static boolean verifyFileSIG(String JavaDoc file
220                                         , StringBuffer JavaDoc signature
221                                         , PublicKey JavaDoc verifyKey
222                                         , String JavaDoc signame)
223             throws CryptoException {
224
225         FileInputStream fis = null;
226
227         try {
228             fis = new FileInputStream(file);
229
230             // verify SIG
231
return verifySIG(fis, signature, verifyKey, signame, BUFFERSIZE_FILE);
232
233         } catch (IOException ioe) {
234             ioe.printStackTrace();
235             throw new CryptoException(ioe.getMessage());
236         } finally {
237             if (fis != null) {
238                 // close outputstream
239
try {
240                     fis.close();
241                 } catch (IOException e) {
242                     ;
243                 }
244             }
245         }
246     }
247
248     /**
249      * Verifies a signature from any inputstream
250      *
251      * @param is inputstream to verify
252      * @param signature the signature (in BASE64 format)
253      * @param verifyKey the verification key
254      * @param signame Signature algorithm (e.g. RIPEMD160WithRSA/ISO9796-2)
255      * @param bufferlength buffer length in bytes
256      * @return true (verified) or false (invalid)
257      * @throws IOException I/O errors
258      * @throws CryptoException for all encryption errors
259      **/

260     public static boolean verifySIG(InputStream is
261                                     , StringBuffer JavaDoc signature
262                                     , PublicKey JavaDoc verifyKey
263                                     , String JavaDoc signame
264                                     , int bufferlength)
265             throws CryptoException, IOException {
266         try {
267             // Add Bouncy Castle provider
268
Security.addProvider(new BouncyCastleProvider());
269
270             Signature JavaDoc sig = Signature.getInstance(signame, "BC");
271             byte[] sigBytes = Base64.decode(signature.toString());
272
273             sig.initVerify(verifyKey);
274             byte[] buffer = new byte[bufferlength];
275             int length = 0;
276
277             // Read bytes into buffer
278
while ((length = is.read(buffer)) != -1) {
279                 sig.update(buffer, 0, length);
280             }
281
282             if (!sig.verify(sigBytes)) {
283                 return false;
284             } else {
285                 return true;
286             }
287         } catch (IOException ioe) {
288             ioe.printStackTrace();
289             throw new IOException(ioe.getMessage());
290         } catch (Exception JavaDoc ex) {
291             ex.printStackTrace();
292             throw new CryptoException(ex.getMessage());
293         }
294     }
295 }
296
Popular Tags