KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2   Name: PBECrypt.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
20 package net.sourceforge.jcetaglib.lib;
21
22 import net.sourceforge.jcetaglib.exceptions.CryptoException;
23 import org.bouncycastle.jce.provider.BouncyCastleProvider;
24 import org.bouncycastle.util.encoders.Base64;
25
26 import javax.crypto.*;
27 import javax.crypto.spec.PBEKeySpec;
28 import javax.crypto.spec.PBEParameterSpec;
29 import java.io.*;
30 import java.security.SecureRandom JavaDoc;
31 import java.security.Security JavaDoc;
32
33 /**
34  * PBE (Password-based) encryption & decryption routines for use with BouncyCastle JCE provider
35  *
36  * @author Gert Van Ham
37  * @author hamgert@users.sourceforge.net
38  * @author http://jcetaglib.sourceforge.net
39  * @version $Id: PBECrypt.java,v 1.3 2004/04/15 07:28:25 hamgert Exp $
40  */

41 public class PBECrypt {
42     // iteration count for PBE encryption
43
private static int PBE_COUNT = 20;
44
45     // buffersizes in bytes
46
private static int BUFFERSIZE_TEXT = 64;
47     private static int BUFFERSIZE_FILE = 8192;
48
49     /**
50      * Encrypts a string with PBE and returns the ciphered text in BASE64 format.
51      *
52      * @param text the text to encrypt
53      * @param passphrase password or passphrase
54      * @param algorithm encryption algorithm (e.g. "PBEWithSHAAndIDEA-CBC")
55      * @return the cipherstring in BASE64 format
56      * @exception net.sourceforge.jcetaglib.exceptions.CryptoException for all encryption errors
57      **/

58     public static StringBuffer JavaDoc encrypt(StringBuffer JavaDoc text
59                                        , StringBuffer JavaDoc passphrase
60                                        , String JavaDoc algorithm) throws CryptoException {
61
62         return encrypt(text, passphrase, null, algorithm);
63     }
64
65     /**
66      * Encrypts a string with PBE and returns the ciphered text in BASE64 format.
67      *
68      * @param text the text to encrypt
69      * @param passphrase password or passphrase
70      * @param seed the seed for SecureRandom
71      * @param algorithm encryption algorithm (e.g. "PBEWithSHAAndIDEA-CBC")
72      * @return the cipherstring in BASE64 format
73      * @exception net.sourceforge.jcetaglib.exceptions.CryptoException for all encryption errors
74      **/

75     public static StringBuffer JavaDoc encrypt(StringBuffer JavaDoc text
76                                        , StringBuffer JavaDoc passphrase
77                                        , byte[] seed
78                                        , String JavaDoc algorithm) throws CryptoException {
79
80         ByteArrayOutputStream bao = null;
81         DataOutputStream dao = null;
82
83         try {
84             bao = new ByteArrayOutputStream();
85             dao = new DataOutputStream(bao);
86
87             // encrypt text
88
encrypt(new ByteArrayInputStream(text.toString().getBytes()), dao, seed, passphrase, algorithm, BUFFERSIZE_TEXT);
89             return new StringBuffer JavaDoc(new String JavaDoc(Base64.encode(bao.toByteArray())));
90         } catch (IOException ioe) {
91             ioe.printStackTrace();
92             throw new CryptoException(ioe.getMessage());
93         } finally {
94             if (dao != null) {
95                 // close outputstream
96
try {
97                     dao.close();
98                 } catch (IOException e) {
99                     ;
100                 }
101             }
102         }
103     }
104
105     /**
106      * Encrypts any inputstream with PBE (password-based encryption)
107      *
108      * @param is any inputstream
109      * @param daos ciphered outputstream
110      * @param seed seed for SecureRandom (optional)
111      * @param passphrase the password or passphrase
112      * @param algorithm encryption algorithm (e.g. "PBEWithSHAAndIDEA-CBC")
113      * @param bufferlength buffer length in bytes
114      * @exception net.sourceforge.jcetaglib.exceptions.CryptoException for all errors
115      **/

116     public static void encrypt(InputStream is
117                                , DataOutputStream daos
118                                , byte[] seed
119                                , StringBuffer JavaDoc passphrase
120                                , String JavaDoc algorithm
121                                , int bufferlength)
122             throws CryptoException, IOException {
123
124         CipherOutputStream cStr = null;
125         PBEKeySpec pbeKeySpec;
126         PBEParameterSpec pbeParamSpec;
127         SecretKeyFactory keyFac;
128         SecretKey pbeKey;
129         Cipher pbeCipher;
130
131         try {
132             // Add Bouncy Castle provider
133
Security.addProvider(new BouncyCastleProvider());
134
135             // Create a random salt of 64 bits (8 bytes)
136
byte[] randomsalt = new byte[8];
137             SecureRandom JavaDoc sr = Seed.getSecureRandom(seed);
138             sr.nextBytes(randomsalt);
139
140             // Create PBE parameter set
141
pbeParamSpec = new PBEParameterSpec(randomsalt, PBE_COUNT);
142
143             pbeKeySpec = new PBEKeySpec(passphrase.toString().toCharArray());
144             keyFac = SecretKeyFactory.getInstance(algorithm);
145             pbeKey = keyFac.generateSecret(pbeKeySpec);
146
147             // Create PBE Cipher
148
pbeCipher = Cipher.getInstance(algorithm);
149
150             // Initialize PBE Cipher with key and parameters
151
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
152
153             // Create CipherOutputStream using PBE cipher
154
cStr = new CipherOutputStream(daos, pbeCipher);
155
156             // first, write the salt to the file (8 bytes or 64 bits)
157
daos.write(randomsalt);
158
159             // Read input bytes into buffer and run them through the cipher stream
160
byte[] buffer = new byte[bufferlength];
161             int length = 0;
162             while ((length = is.read(buffer)) != -1) {
163                 cStr.write(buffer, 0, length);
164             }
165         } catch (IOException ioe) {
166             ioe.printStackTrace();
167             throw new IOException(ioe.getMessage());
168         } catch (Exception JavaDoc ex) {
169             ex.printStackTrace();
170             throw new CryptoException(ex.getMessage());
171         } finally {
172             if (cStr != null) {
173                 try {
174                     cStr.close();
175                 } catch (IOException ioe) {
176                     ;
177                 }
178             }
179         }
180     }
181
182     /**
183      * Encrypts a file with PBE and creates a new file with the result.
184      *
185      * @param file the file to encrypt
186      * @param file the encrypted file
187      * @param passphrase password or passphrase
188      * @param algorithm encryption algorithm (e.g. "PBEWithSHAAndIDEA-CBC")
189      * @exception IOException I/O errors
190      * @exception net.sourceforge.jcetaglib.exceptions.CryptoException for all encryption errors
191      **/

192     public static void encryptFile(String JavaDoc file
193                                    , String JavaDoc newfile
194                                    , StringBuffer JavaDoc passphrase
195                                    , String JavaDoc algorithm) throws CryptoException, IOException {
196         encryptFile(file, newfile, passphrase, null, algorithm);
197     }
198
199     /**
200      * Encrypts a file with PBE and creates a new file with the result.
201      *
202      * @param file the file to encrypt
203      * @param newfile the encrypted file
204      * @param passphrase password or passphrase
205      * @param seed the seed for SecureRandom
206      * @param algorithm encryption algorithm (e.g. "PBEWithSHAAndIDEA-CBC")
207      * @exception IOException I/O errors
208      * @exception net.sourceforge.jcetaglib.exceptions.CryptoException for all encryption errors
209      **/

210     public static void encryptFile(String JavaDoc file
211                                    , String JavaDoc newfile
212                                    , StringBuffer JavaDoc passphrase
213                                    , byte[] seed
214                                    , String JavaDoc algorithm) throws CryptoException, IOException {
215
216         FileInputStream fis = null;
217         FileOutputStream fos = null;
218         DataOutputStream dao = null;
219
220         try {
221             fis = new FileInputStream(file);
222
223             fos = new FileOutputStream(newfile);
224             dao = new DataOutputStream(fos);
225
226             // encrypt file
227
encrypt(fis, dao, seed, passphrase, algorithm, BUFFERSIZE_FILE);
228
229         } catch (IOException ioe) {
230             ioe.printStackTrace();
231             throw new IOException(ioe.getMessage());
232         } finally {
233             if (dao != null) {
234                 // close outputstream
235
try {
236                     dao.close();
237                 } catch (IOException e) {
238                     ;
239                 }
240             }
241             if (fis != null) {
242                 // close outputstream
243
try {
244                     fis.close();
245                 } catch (IOException e) {
246                     ;
247                 }
248             }
249         }
250     }
251
252     /**
253      * Decrypts a ciphertext with PBE
254      *
255      * @param text the ciphertext
256      * @param passphrase password or passphrase
257      * @param algorithm encryption algorithm (e.g. "PBEWithSHAAndIDEA-CBC")
258      * @return the decrypted plaintext
259      * @throws net.sourceforge.jcetaglib.exceptions.CryptoException for all encryption errors
260      */

261     public static StringBuffer JavaDoc decrypt(StringBuffer JavaDoc text
262                                        , StringBuffer JavaDoc passphrase
263                                        , String JavaDoc algorithm) throws CryptoException {
264
265         ByteArrayOutputStream bao = null;
266         DataOutputStream dao = null;
267
268         try {
269             bao = new ByteArrayOutputStream();
270             dao = new DataOutputStream(bao);
271
272             // decrypt
273
decrypt(new ByteArrayInputStream(Base64.decode(text.toString())), dao, passphrase, algorithm, BUFFERSIZE_TEXT);
274
275             return new StringBuffer JavaDoc(new String JavaDoc(bao.toByteArray()));
276
277         } catch (IOException ioe) {
278             ioe.printStackTrace();
279             throw new CryptoException(ioe.getMessage());
280         } finally {
281             if (dao != null) {
282                 // close outputstream
283
try {
284                     dao.close();
285                 } catch (IOException e) {
286                     ;
287                 }
288             }
289         }
290     }
291
292     /**
293      * Decrypts any inputstream with PBE
294      *
295      * @param is the ciphered inputstream
296      * @param daos deciphered outputstream
297      * @param passphrase password or passphrase
298      * @param algorithm encryption algorithm (e.g. "PBEWithSHAAndIDEA-CBC")
299      * @param bufferlength buffer length in bytes
300      * @throws net.sourceforge.jcetaglib.exceptions.CryptoException encryption errors
301      * @throws IOException I/O errors
302      */

303     public static void decrypt(InputStream is
304                                , DataOutputStream daos
305                                , StringBuffer JavaDoc passphrase
306                                , String JavaDoc algorithm
307                                , int bufferlength)
308             throws CryptoException, IOException {
309
310         CipherInputStream ciStr = null;
311         PBEKeySpec pbeKeySpec;
312         PBEParameterSpec pbeParamSpec;
313         SecretKeyFactory keyFac;
314         SecretKey pbeKey;
315         Cipher pbeCipher;
316
317         try {
318             // Add Bouncy Castle provider
319
Security.addProvider(new BouncyCastleProvider());
320
321             // read the salt
322
byte[] randomsalt = new byte[8];
323             is.read(randomsalt);
324
325             // Create PBE parameter set
326
pbeParamSpec = new PBEParameterSpec(randomsalt, PBE_COUNT);
327
328             pbeKeySpec = new PBEKeySpec(passphrase.toString().toCharArray());
329             keyFac = SecretKeyFactory.getInstance(algorithm);
330             pbeKey = keyFac.generateSecret(pbeKeySpec);
331
332             // Create PBE Cipher
333
pbeCipher = Cipher.getInstance(algorithm);
334
335             // Initialize PBE Cipher with key and parameters
336
pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);
337
338             // Initialize cipher inputstream
339
ciStr = new CipherInputStream(is, pbeCipher);
340
341             // Read bytes and run them through cipher
342
byte[] buffer = new byte[bufferlength];
343             int length = 0;
344             while ((length = ciStr.read(buffer)) != -1) {
345                 daos.write(buffer, 0, length);
346             }
347         } catch (IOException ioe) {
348             ioe.printStackTrace();
349             throw new IOException(ioe.getMessage());
350         } catch (Exception JavaDoc ex) {
351             ex.printStackTrace();
352             throw new CryptoException(ex.getMessage());
353         } finally {
354             if (ciStr != null) {
355                 try {
356                     ciStr.close();
357                 } catch (IOException ioe) {
358                     ;
359                 }
360             }
361         }
362     }
363
364     /**
365      * Decrypts a ciphered file with PBE
366      *
367      * @param file the file to decrypt
368      * @param file the deciphered file
369      * @param passphrase the password or passphrase
370      * @param algorithm encryption algorithm (e.g. "PBEWithSHAAndIDEA-CBC")
371      * @exception net.sourceforge.jcetaglib.exceptions.CryptoException for all encryption errors
372      * @exception IOException I/O errors
373      **/

374     public static void decryptFile(String JavaDoc file
375                                    , String JavaDoc newfile
376                                    , StringBuffer JavaDoc passphrase
377                                    , String JavaDoc algorithm) throws CryptoException, IOException {
378
379         FileInputStream fis = null;
380         FileOutputStream fos = null;
381         DataOutputStream dao = null;
382
383         try {
384             fis = new FileInputStream(file);
385
386             fos = new FileOutputStream(newfile);
387             dao = new DataOutputStream(fos);
388
389             // decrypt file
390
decrypt(fis, dao, passphrase, algorithm, BUFFERSIZE_FILE);
391
392         } catch (IOException ioe) {
393             ioe.printStackTrace();
394             throw new IOException(ioe.getMessage());
395         } finally {
396             if (dao != null) {
397                 // close outputstream
398
try {
399                     dao.close();
400                 } catch (IOException e) {
401                     ;
402                 }
403             }
404             if (fis != null) {
405                 // close inputstream
406
try {
407                     fis.close();
408                 } catch (IOException e) {
409                     ;
410                 }
411             }
412         }
413     }
414 }
415
Popular Tags