KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > lightcrypto > PBECrypt


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

20
21 package net.sourceforge.lightcrypto;
22
23 import org.bouncycastle.crypto.PBEParametersGenerator;
24 import org.bouncycastle.crypto.BufferedBlockCipher;
25 import org.bouncycastle.crypto.CipherParameters;
26 import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
27 import org.bouncycastle.crypto.modes.CBCBlockCipher;
28 import org.bouncycastle.crypto.engines.TwofishEngine;
29 import org.bouncycastle.crypto.digests.SHA1Digest;
30 import org.bouncycastle.crypto.generators.PKCS12ParametersGenerator;
31 import org.bouncycastle.util.encoders.Base64;
32
33 import java.io.*;
34 import java.security.SecureRandom JavaDoc;
35
36 /**
37  * PBE (Password-based) encryption & decryption routines for use with the BouncyCastle lightweight API
38  *
39  * @author Gert Van Ham
40  * @author hamgert@users.sourceforge.net
41  * @author http://jcetaglib.sourceforge.net
42  * @version $Id: PBECrypt.java,v 1.1 2003/10/28 20:12:53 hamgert Exp $
43  */

44
45 public class PBECrypt {
46     private static int BUFFERSIZE_TEXT = 64;
47     private static int BUFFERSIZE_FILE = 8192;
48
49     private static int PBECount = 20;
50     private static int PBEKeyLength = 256;
51
52     /**
53      * Encrypts a string with PBE and returns
54      * the ciphered text in BASE64 format.
55      *
56      * @param text the text to encrypt
57      * @param passphrase password or passphrase
58      * @return the cipherstring in BASE64 format
59      * @exception IOException I/O errors
60      * @exception CryptoException for all encryption errors
61      **/

62     public static StringBuffer JavaDoc encrypt(
63             StringBuffer JavaDoc text
64             , StringBuffer JavaDoc passphrase
65             ) throws CryptoException, IOException {
66
67         return encrypt(text, passphrase, null);
68     }
69
70     /**
71      * Encrypts a string with PBE and returns
72      * the ciphered text in BASE64 format.
73      *
74      * @param text the text to encrypt
75      * @param passphrase password or passphrase
76      * @param seed the seed for SecureRandom
77      * @return the cipherstring in BASE64 format
78      * @exception IOException I/O errors
79      * @exception CryptoException for all encryption errors
80      **/

81     public static StringBuffer JavaDoc encrypt(
82             StringBuffer JavaDoc text
83             , StringBuffer JavaDoc passphrase
84             , StringBuffer JavaDoc seed
85             ) throws CryptoException, IOException {
86
87         ByteArrayOutputStream bao = new ByteArrayOutputStream();
88         DataOutputStream dao = new DataOutputStream(bao);
89
90         // encrypt text
91
encrypt(new ByteArrayInputStream(text.toString().getBytes()), dao, passphrase, seed, BUFFERSIZE_TEXT);
92
93         StringBuffer JavaDoc result = new StringBuffer JavaDoc(new String JavaDoc(Base64.encode(bao.toByteArray())));
94
95         // close outputstream
96
dao.flush();
97         dao.close();
98
99         return result;
100     }
101
102     /**
103      * Encrypts any inputstream with PBE and returns
104      * the ciphered inputstream as a DataOutputStream.
105      *
106      * @param is the inputstream to encrypt
107      * @param daos outputstream for the ciphertext
108      * @param passphrase password or passphrase
109      * @param bufferlength buffer length in bytes
110      * @param seed the seed for SecureRandom
111      * @exception CryptoException for all encryption errors
112      **/

113     public static void encrypt(
114             InputStream is
115             , DataOutputStream daos
116             , StringBuffer JavaDoc passphrase
117             , StringBuffer JavaDoc seed
118             , int bufferlength
119             ) throws CryptoException {
120
121         try {
122             SecureRandom JavaDoc sr = new SecureRandom JavaDoc();
123
124             // set seed if available
125
if (seed != null && !seed.equals("")) {
126                 sr.setSeed(seed.toString().getBytes());
127             }
128
129             // create random salt
130
byte[] randomsalt = new byte[8];
131             sr.nextBytes(randomsalt);
132
133             // write the randomsalt
134
daos.write(randomsalt);
135
136             // create the PBE cipher
137
PBEParametersGenerator generator = new PKCS12ParametersGenerator(new SHA1Digest());
138             generator.init(PBEParametersGenerator.PKCS12PasswordToBytes(passphrase.toString().toCharArray()), randomsalt, PBECount);
139
140             TwofishEngine blockCipher = new TwofishEngine();
141             CBCBlockCipher cbcCipher = new CBCBlockCipher(blockCipher);
142             BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(cbcCipher);
143
144             CipherParameters param = generator.generateDerivedParameters(PBEKeyLength,128);
145
146             // encrypt with PBE
147
cipher.init(true, param);
148
149             byte[] buffer = new byte[bufferlength];
150             int length = cipher.getOutputSize(bufferlength);
151             byte[] result = new byte[length];
152             int outputLen = 0;
153
154             // read bytes into buffer and feed these bytes into the cipher
155
while ((length = is.read(buffer)) != -1) {
156                 outputLen = cipher.processBytes(buffer, 0, length, result, 0);
157
158                 if (outputLen > 0) {
159                     daos.write(result, 0, outputLen);
160                 }
161             }
162
163             // doFinal for encrypting last bytes
164
outputLen = cipher.doFinal(result, 0);
165             if (outputLen > 0) {
166                 daos.write(result, 0, outputLen);
167             }
168
169         } catch (Exception JavaDoc ex) {
170             ex.printStackTrace();
171             throw new CryptoException(ex.getMessage());
172         }
173     }
174
175     /**
176      * Encrypts a file with PBE and creates
177      * a new file with the result.
178      *
179      * @param file the file to encrypt
180      * @param file the encrypted file
181      * @param passphrase password or passphrase
182      * @exception IOException I/O errors
183      * @exception CryptoException for all encryption errors
184      **/

185     public static void encryptFile(
186             String JavaDoc file
187             , String JavaDoc newfile
188             , StringBuffer JavaDoc passphrase
189             ) throws CryptoException, IOException {
190         encryptFile(file, newfile, passphrase, null);
191     }
192
193     /**
194      * Encrypts a file with PBE and creates
195      * a new file with the result.
196      *
197      * @param file the file to encrypt
198      * @param file the encrypted file
199      * @param passphrase password or passphrase
200      * @param seed the seed for SecureRandom
201      * @exception IOException I/O errors
202      * @exception CryptoException for all encryption errors
203      **/

204     public static void encryptFile(
205             String JavaDoc file
206             , String JavaDoc newfile
207             , StringBuffer JavaDoc passphrase
208             , StringBuffer JavaDoc seed
209             ) throws CryptoException, IOException {
210
211         FileInputStream fis = new FileInputStream(file);
212         FileOutputStream fos = new FileOutputStream(newfile);
213
214         DataOutputStream dao = new DataOutputStream(fos);
215
216         // encrypt file
217
encrypt(fis, dao, passphrase, seed, BUFFERSIZE_FILE);
218
219         // close outputstream
220
dao.flush();
221         dao.close();
222
223         // close inputstream
224
fis.close();
225         fos.close();
226     }
227
228     /**
229      * Decrypts a ciphered BASE64 string with PBE
230      *
231      * @param text the text to decipher
232      * @param passphrase the password or passphrase
233      * @return the decipher string (plaintext)
234      * @exception CryptoException for all encryption errors
235      * @exception IOException I/O errors
236      **/

237     public static StringBuffer JavaDoc decrypt(
238             StringBuffer JavaDoc text
239             , StringBuffer JavaDoc passphrase
240             ) throws CryptoException, IOException {
241
242         ByteArrayOutputStream bao = new ByteArrayOutputStream();
243         DataOutputStream dao = new DataOutputStream(bao);
244
245         // decrypt
246
decrypt(new ByteArrayInputStream(Base64.decode(text.toString())), dao, passphrase, BUFFERSIZE_TEXT);
247
248         //close outputstream
249
dao.flush();
250         dao.close();
251
252         return new StringBuffer JavaDoc(new String JavaDoc(bao.toByteArray()));
253     }
254
255     /**
256      * Decrypts a ciphered file with PBE
257      *
258      * @param file the file to decrypt
259      * @param file the deciphered file
260      * @param passphrase the password or passphrase
261      * @exception CryptoException for all encryption errors
262      * @exception IOException I/O errors
263      **/

264     public static void decryptFile(
265             String JavaDoc file
266             , String JavaDoc newfile
267             , StringBuffer JavaDoc passphrase
268             ) throws CryptoException, IOException {
269
270         FileInputStream fis = new FileInputStream(file);
271         FileOutputStream fos = new FileOutputStream(newfile);
272         DataOutputStream dao = new DataOutputStream(fos);
273
274         // decrypt file
275
decrypt(fis, dao, passphrase, BUFFERSIZE_FILE);
276
277         // close outputstream
278
dao.flush();
279         dao.close();
280
281         // close inputstream
282
fis.close();
283         fos.close();
284     }
285
286     /**
287      * Decrypts a ciphered inputstream with PBE
288      *
289      * @param is the inputstream to decipher
290      * @param daos outputstream for the plaintext
291      * @param passphrase the password or passphrase
292      * @param bufferlength buffer length in bytes
293      * @exception CryptoException for all encryption errors
294      **/

295     public static void decrypt(
296             InputStream is
297             , DataOutputStream daos
298             , StringBuffer JavaDoc passphrase
299             , int bufferlength
300             ) throws CryptoException {
301
302         try {
303             // read the salt
304
byte[] randomsalt = new byte[8];
305             is.read(randomsalt);
306
307             // create the PBE cipher
308
PBEParametersGenerator generator = new PKCS12ParametersGenerator(new SHA1Digest());
309             generator.init(PBEParametersGenerator.PKCS12PasswordToBytes(passphrase.toString().toCharArray()), randomsalt, PBECount);
310
311             TwofishEngine blockCipher = new TwofishEngine();
312             CBCBlockCipher cbcCipher = new CBCBlockCipher(blockCipher);
313             BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(cbcCipher);
314
315             CipherParameters param = generator.generateDerivedParameters(PBEKeyLength,128);
316
317             // decrypt with PBE
318
cipher.init(false, param);
319
320             byte[] buffer = new byte[bufferlength];
321             int length = cipher.getOutputSize(bufferlength);
322             byte[] result = new byte[length];
323             int outputLen = 0;
324
325             // read bytes into buffer and feed these bytes into the cipher
326
while ((length = is.read(buffer)) != -1) {
327                 outputLen = cipher.processBytes(buffer, 0, length, result, 0);
328
329                 if (outputLen > 0) {
330                     daos.write(result, 0, outputLen);
331                 }
332             }
333
334             // doFinal for encrypting last bytes
335
outputLen = cipher.doFinal(result, 0);
336             if (outputLen > 0) {
337                 daos.write(result, 0, outputLen);
338             }
339
340         } catch (Exception JavaDoc ex) {
341             ex.printStackTrace();
342             throw new CryptoException(ex.getMessage());
343         }
344     }
345 }
346
Popular Tags