KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2   Name: net.sourceforge.lightcrypto.Crypt
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.BufferedBlockCipher;
24 import org.bouncycastle.crypto.engines.AESLightEngine;
25 import org.bouncycastle.crypto.modes.CBCBlockCipher;
26 import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
27 import org.bouncycastle.crypto.params.KeyParameter;
28 import org.bouncycastle.crypto.params.ParametersWithIV;
29 import org.bouncycastle.util.encoders.Base64;
30
31 import java.io.*;
32 import java.security.SecureRandom JavaDoc;
33
34 /**
35  * Encryption & decryption routines for use with the BouncyCastle lightweight API
36  *
37  * @author Gert Van Ham
38  * @author hamgert@users.sourceforge.net
39  * @author http://jcetaglib.sourceforge.net
40  * @version $Id: Crypt.java,v 1.2 2003/10/05 11:41:29 hamgert Exp $
41  */

42
43 public class Crypt {
44     private static int BUFFERSIZE_TEXT = 64;
45     private static int BUFFERSIZE_FILE = 8192;
46
47     /**
48      * Encrypts a string with a symmetric key (AES light engine, CBC mode, PKCS7 padding) and returns
49      * the ciphered text in BASE64 format.
50      *
51      * @param text the text to encrypt
52      * @param keybytes the symmetric key (which generated with the net.sourceforge.lightcrypto.Key object)
53      * @return the cipherstring in BASE64 format
54      * @exception IOException I/O errors
55      * @exception CryptoException for all encryption errors
56      **/

57     public static StringBuffer JavaDoc encrypt(
58             StringBuffer JavaDoc text
59             , SafeObject keybytes
60             ) throws CryptoException, IOException {
61
62         return encrypt(text, keybytes, null);
63     }
64
65     /**
66      * Encrypts a string with a symmetric key (AES light engine, CBC mode, PKCS7 padding) and returns
67      * the ciphered text in BASE64 format.
68      *
69      * @param text the text to encrypt
70      * @param keybytes the symmetric key (which generated with the net.sourceforge.lightcrypto.Key object)
71      * @param seed the seed for SecureRandom
72      * @return the cipherstring in BASE64 format
73      * @exception IOException I/O errors
74      * @exception CryptoException for all encryption errors
75      **/

76     public static StringBuffer JavaDoc encrypt(
77             StringBuffer JavaDoc text
78             , SafeObject keybytes
79             , StringBuffer JavaDoc seed
80             ) throws CryptoException, IOException {
81
82         ByteArrayOutputStream bao = new ByteArrayOutputStream();
83         DataOutputStream dao = new DataOutputStream(bao);
84
85         // encrypt text
86
encrypt(new ByteArrayInputStream(text.toString().getBytes()), dao, keybytes, seed, BUFFERSIZE_TEXT);
87
88         StringBuffer JavaDoc result = new StringBuffer JavaDoc(new String JavaDoc(Base64.encode(bao.toByteArray())));
89
90         // close outputstream
91
dao.flush();
92         dao.close();
93
94         return result;
95     }
96
97     /**
98      * Encrypts a file with a symmetric key (AES light engine, CBC mode, PKCS7 padding) and creates
99      * a new file with the result.
100      *
101      * @param file the file to encrypt
102      * @param file the encrypted file
103      * @param keybytes the symmetric key (which generated with the net.sourceforge.lightcrypto.Key object)
104      * @exception IOException I/O errors
105      * @exception CryptoException for all encryption errors
106      **/

107     public static void encryptFile(
108             String JavaDoc file
109             , String JavaDoc newfile
110             , SafeObject keybytes
111             ) throws CryptoException, IOException {
112         encryptFile(file, newfile, keybytes, null);
113     }
114
115     /**
116      * Encrypts a file with a symmetric key (AES light engine, CBC mode, PKCS7 padding) and creates
117      * a new file with the result.
118      *
119      * @param file the file to encrypt
120      * @param file the encrypted file
121      * @param keybytes the symmetric key (which generated with the net.sourceforge.lightcrypto.Key object)
122      * @param seed the seed for SecureRandom
123      * @exception IOException I/O errors
124      * @exception CryptoException for all encryption errors
125      **/

126     public static void encryptFile(
127             String JavaDoc file
128             , String JavaDoc newfile
129             , SafeObject keybytes
130             , StringBuffer JavaDoc seed
131             ) throws CryptoException, IOException {
132
133         FileInputStream fis = new FileInputStream(file);
134         FileOutputStream fos = new FileOutputStream(newfile);
135
136         DataOutputStream dao = new DataOutputStream(fos);
137
138         // encrypt file
139
encrypt(fis, dao, keybytes, seed, BUFFERSIZE_FILE);
140
141         // close outputstream
142
dao.flush();
143         dao.close();
144
145         // close inputstream
146
fis.close();
147         fos.close();
148     }
149
150     /**
151      * Encrypts any inputstream with a symmetric key (AES light engine, CBC mode, PKCS7 padding) and returns
152      * the ciphered inputstream as a ByteArrayOutputStream
153      *
154      * @param is the inputstream to encrypt
155      * @param daos outputstream for the ciphertext
156      * @param keybytes the symmetric key (which generated with the net.sourceforge.lightcrypto.Key object)
157      * @param seed the seed for SecureRandom
158      * @param bufferlength buffer length in bytes
159      * @exception CryptoException for all encryption errors
160      **/

161     public static void encrypt(
162             InputStream is
163             , DataOutputStream daos
164             , SafeObject keybytes
165             , StringBuffer JavaDoc seed
166             , int bufferlength
167             ) throws CryptoException {
168
169         KeyParameter key = null;
170
171         try {
172             SecureRandom JavaDoc sr = new SecureRandom JavaDoc();
173
174             // set seed if available
175
if (seed != null && !seed.equals("")) {
176                 sr.setSeed(seed.toString().getBytes());
177             }
178
179             // Initialize the AES cipher ("light" engine) in CBC mode with PKCS7 padding
180
AESLightEngine blockCipher = new AESLightEngine();
181             CBCBlockCipher cbcCipher = new CBCBlockCipher(blockCipher);
182             BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(cbcCipher);
183
184             // Create an IV of random data.
185
byte[] iv = new byte[blockCipher.getBlockSize()];
186             sr.nextBytes(iv);
187
188             // use the keybytes to create a key
189
key = new KeyParameter(keybytes.getBytes());
190             // use the IV and key to create cipherparameters
191
ParametersWithIV ivparam = new ParametersWithIV(key, iv);
192
193             // write the IV to the outputstream
194
daos.write(iv, 0, iv.length);
195
196             // Concatenate the IV and the message.
197
byte[] buffer = new byte[bufferlength];
198             int length = cipher.getOutputSize(bufferlength);
199             byte[] result = new byte[length];
200             int outputLen = 0;
201
202             // initialize the cipher for encrypting with the key and IV
203
cipher.init(true, ivparam);
204
205             // read bytes into buffer and feed these bytes into the cipher
206
while ((length = is.read(buffer)) != -1) {
207                 outputLen = cipher.processBytes(buffer, 0, length, result, 0);
208
209                 if (outputLen > 0) {
210                     daos.write(result, 0, outputLen);
211                 }
212             }
213
214             // doFinal for encrypting last bytes
215
outputLen = cipher.doFinal(result, 0);
216             if (outputLen > 0) {
217                 daos.write(result, 0, outputLen);
218             }
219
220         } catch (Exception JavaDoc ex) {
221             ex.printStackTrace();
222             throw new CryptoException(ex.getMessage());
223         } finally {
224             // clean sensitive information from memory
225
key = null;
226             if (seed != null) {
227                 Clean.blank(seed);
228                 seed = null;
229             }
230         }
231     }
232
233     /**
234      * Decrypts a ciphered BASE64 string with a symmetric key (AES light engine, CBC mode, PKCS7 padding)
235      *
236      * @param text the text to decipher
237      * @param keybytes the symmetric key (which generated with the net.sourceforge.lightcrypto.Key object)
238      * @return the decipher string (plaintext)
239      * @exception CryptoException for all encryption errors
240      * @exception IOException I/O errors
241      **/

242     public static StringBuffer JavaDoc decrypt(
243             StringBuffer JavaDoc text
244             , SafeObject keybytes
245             ) throws CryptoException, IOException {
246
247         ByteArrayOutputStream bao = new ByteArrayOutputStream();
248         DataOutputStream dao = new DataOutputStream(bao);
249
250         // decrypt
251
decrypt(new ByteArrayInputStream(Base64.decode(text.toString())), dao, keybytes, BUFFERSIZE_TEXT);
252
253         //close outputstream
254
dao.flush();
255         dao.close();
256
257         return new StringBuffer JavaDoc(new String JavaDoc(bao.toByteArray()));
258     }
259
260     /**
261      * Decrypts a ciphered file with a symmetric key (AES light engine, CBC mode, PKCS7 padding)
262      *
263      * @param file the file to decrypt
264      * @param file the deciphered file
265      * @param keybytes the symmetric key (which generated with the net.sourceforge.lightcrypto.Key object)
266      * @exception CryptoException for all encryption errors
267      * @exception IOException I/O errors
268      **/

269     public static void decryptFile(
270             String JavaDoc file
271             , String JavaDoc newfile
272             , SafeObject keybytes
273             ) throws CryptoException, IOException {
274
275         FileInputStream fis = new FileInputStream(file);
276         FileOutputStream fos = new FileOutputStream(newfile);
277         DataOutputStream dao = new DataOutputStream(fos);
278
279         // decrypt file
280
decrypt(fis, dao, keybytes, BUFFERSIZE_FILE);
281
282         // close outputstream
283
dao.flush();
284         dao.close();
285
286         // close inputstream
287
fis.close();
288         fos.close();
289     }
290
291     /**
292      * Decrypts a ciphered inputstream with a symmetric key (AES light engine, CBC mode, PKCS7 padding)
293      *
294      * @param is the inputstream to decipher
295      * @param daos outputstream for the plaintext
296      * @param keybytes the symmetric key (which generated with the net.sourceforge.lightcrypto.Key object)
297      * @param bufferlength buffer length in bytes
298      * @exception CryptoException for all encryption errors
299      **/

300     public static void decrypt(
301             InputStream is
302             , DataOutputStream daos
303             , SafeObject keybytes
304             , int bufferlength
305             ) throws CryptoException {
306         KeyParameter key = null;
307
308         try {
309             // use the keybytes to create a key
310
key = new KeyParameter(keybytes.getBytes());
311
312             AESLightEngine blockCipher = new AESLightEngine();
313             CBCBlockCipher cbcCipher = new CBCBlockCipher(blockCipher);
314             BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(cbcCipher);
315
316             // read the IV from the inputstream
317
byte[] iv = new byte[blockCipher.getBlockSize()];
318             is.read(iv);
319
320             // use the IV and key to create cipherparameters
321
ParametersWithIV ivparam = new ParametersWithIV(key, iv);
322
323             byte[] buffer = new byte[bufferlength];
324             int length = cipher.getOutputSize(buffer.length);
325             byte[] result = new byte[length];
326             int outputLen = 0;
327
328             // initialize the cipher for decrypting ith the key and IV
329
cipher.init(false, ivparam);
330
331             // read bytes into buffer and feed these bytes into the cipher
332
while ((length = is.read(buffer)) != -1) {
333                 outputLen = cipher.processBytes(buffer, 0, length, result, 0);
334
335                 if (outputLen > 0) {
336                     daos.write(result, 0, outputLen);
337                 }
338             }
339
340             // doFinal for encrypting last bytes
341
outputLen = cipher.doFinal(result, 0);
342             if (outputLen > 0) {
343                 daos.write(result, 0, outputLen);
344             }
345
346         } catch (Exception JavaDoc ex) {
347             ex.printStackTrace();
348             throw new CryptoException(ex.getMessage());
349
350         } finally {
351             // clean sensitive information from memory
352
key = null;
353         }
354     }
355 }
356
Popular Tags