KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2   Name: net.sourceforge.lightcrypto.Macs
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.util.encoders.Base64;
24 import org.bouncycastle.crypto.macs.CBCBlockCipherMac;
25 import org.bouncycastle.crypto.engines.AESLightEngine;
26 import org.bouncycastle.crypto.BlockCipher;
27 import org.bouncycastle.crypto.params.KeyParameter;
28 import org.bouncycastle.crypto.params.ParametersWithIV;
29
30 import java.io.*;
31 import java.security.SecureRandom JavaDoc;
32
33 /**
34  * Create CBC Block Cipher MAC (Message Authentication Code) with IV from text and files
35  *
36  * @author Gert Van Ham
37  * @author hamgert@users.sourceforge.net
38  * @author http://jcetaglib.sourceforge.net
39  * @version $Id: Macs.java,v 1.1 2003/10/05 11:41:29 hamgert Exp $
40  */

41 public class Macs {
42     private static int BUFFERSIZE_TEXT = 64;
43     private static int BUFFERSIZE_FILE = 8192;
44
45     /**
46      * Creates a MAC from a stringbuffer
47      *
48      * @param text creates MAC from this text
49      * @param keybytes the symmetric key
50      * @return MAC in BASE64 format
51      * @throws CryptoException for MAC errors
52      */

53     public static StringBuffer JavaDoc mac(
54             StringBuffer JavaDoc text
55             , SafeObject keybytes
56             ) throws CryptoException {
57         return mac(new ByteArrayInputStream(text.toString().getBytes()), keybytes, null, BUFFERSIZE_TEXT);
58     }
59
60     /**
61      * Creates a MAC from a stringbuffer
62      *
63      * @param text creates MAC from this text
64      * @param keybytes the symmetric key
65      * @param seed the seed for SecureRandom
66      * @return MAC in BASE64 format
67      * @throws CryptoException for MAC errors
68      */

69     public static StringBuffer JavaDoc mac(
70             StringBuffer JavaDoc text
71             , SafeObject keybytes
72             , StringBuffer JavaDoc seed
73             ) throws CryptoException {
74         return mac(new ByteArrayInputStream(text.toString().getBytes()), keybytes, seed, BUFFERSIZE_TEXT);
75     }
76
77     /**
78      * Creates a MAC from a file
79      *
80      * @param file filename
81      * @param keybytes the symmetric key
82      * @return MAC in BASE64 format
83      * @throws CryptoException for MAC errors
84      * @throws FileNotFoundException when the file was not found
85      * @throws IOException when the file could not be opened (or closed)
86      */

87     public static StringBuffer JavaDoc macFromFile(
88             String JavaDoc file
89             , SafeObject keybytes
90             ) throws CryptoException, FileNotFoundException, IOException {
91
92         FileInputStream fis = new FileInputStream(file);
93         StringBuffer JavaDoc res = mac(fis, keybytes, null, BUFFERSIZE_FILE);
94         fis.close();
95         return res;
96     }
97
98     /**
99      * Creates a MAC from a file
100      *
101      * @param file filename
102      * @param keybytes the symmetric key
103      * @param seed the seed for SecureRandom
104      * @return MAC in BASE64 format
105      * @throws CryptoException for MAC errors
106      * @throws FileNotFoundException when the file was not found
107      * @throws IOException when the file could not be opened (or closed)
108      */

109     public static StringBuffer JavaDoc macFromFile(
110             String JavaDoc file
111             , SafeObject keybytes
112             , StringBuffer JavaDoc seed
113             ) throws CryptoException, FileNotFoundException, IOException {
114
115         FileInputStream fis = new FileInputStream(file);
116         StringBuffer JavaDoc res = mac(fis, keybytes, seed, BUFFERSIZE_FILE);
117         fis.close();
118         return res;
119     }
120
121     /**
122      * Creates a MAC from an inputstream
123      *
124      * @param is any inputstream
125      * @param buffersize the buffersize in number of bytes
126      * @return MAC in BASE64 format
127      * @throws CryptoException for MAC errors
128      */

129     public static StringBuffer JavaDoc mac(
130             InputStream is
131             , SafeObject keybytes
132             , StringBuffer JavaDoc seed
133             , int buffersize
134             ) throws CryptoException {
135
136         KeyParameter key = null;
137
138         try {
139             SecureRandom JavaDoc sr = new SecureRandom JavaDoc();
140
141             // set seed if available
142
if (seed != null && !seed.equals("")) {
143                 sr.setSeed(seed.toString().getBytes());
144             }
145
146             BlockCipher cipher = new AESLightEngine();
147             CBCBlockCipherMac mac = new CBCBlockCipherMac(cipher);
148
149             // Create an IV of random data.
150
byte[] iv = new byte[cipher.getBlockSize()];
151             sr.nextBytes(iv);
152
153             // use the keybytes to create a key
154
key = new KeyParameter(keybytes.getBytes());
155             // use the IV and key to create cipherparameters
156
ParametersWithIV ivparam = new ParametersWithIV(key, iv);
157
158             mac.init(ivparam);
159
160             byte[] result = new byte[mac.getMacSize() + iv.length];
161             byte[] buffer = new byte[buffersize];
162             int length = 0;
163
164             // write the IV
165
System.arraycopy(iv, 0, result, 0, iv.length);
166
167             // read bytes into buffer and feed these bytes into Hmac object
168
while ((length = is.read(buffer)) != -1) {
169                 mac.update(buffer, 0, length);
170             }
171
172             mac.doFinal(result, iv.length);
173
174             return new StringBuffer JavaDoc(new String JavaDoc(Base64.encode(result)));
175         } catch (Exception JavaDoc ex) {
176             ex.printStackTrace();
177             throw new CryptoException(ex.getMessage());
178         } finally {
179             // clean sensitive information from memory
180
key = null;
181             if (seed != null) {
182                 Clean.blank(seed);
183                 seed = null;
184             }
185         }
186     }
187
188     /**
189      * Check if a MAC is valid
190      *
191      * @param text the plain text
192      * @param mac the MAC (in BASE64 format)
193      * @param keybytes the MAC (in BASE64 format)
194      * @return true if MAC is valid, false if not
195      * @throws CryptoException for MAC errors
196      */

197     public static boolean macEquals(
198             StringBuffer JavaDoc text
199             , StringBuffer JavaDoc mac
200             , SafeObject keybytes
201             ) throws CryptoException {
202         return macEquals(new ByteArrayInputStream(text.toString().getBytes()), mac, keybytes, BUFFERSIZE_TEXT);
203     }
204
205     /**
206      * Check if a file MAC is valid
207      *
208      * @param file the filename
209      * @param mac the MAC (in BASE64 format)
210      * @param keybytes the MAC (in BASE64 format)
211      * @return true if MAC is valid, false if not
212      * @throws CryptoException for MAC errors
213      * @throws FileNotFoundException when the file was not found
214      * @throws IOException when the file could not be opened (or closed)
215      */

216     public static boolean macEqualsFile(
217             String JavaDoc file
218             , StringBuffer JavaDoc mac
219             , SafeObject keybytes
220             ) throws CryptoException, FileNotFoundException, IOException {
221
222         FileInputStream fis = new FileInputStream(file);
223         boolean res = macEquals(fis, mac, keybytes, BUFFERSIZE_FILE);
224         fis.close();
225         return res;
226     }
227
228     /**
229      * Check if a MAC is valid
230      *
231      * @param is any inputstream containing the plain text
232      * @param mac the MAC (in BASE64 format)
233      * @param keybytes the symmetric key
234      * @param buffersize the buffersize in number of bytes
235      * @return true if MAC is valid, false if not
236      * @throws CryptoException for MAC errors
237      */

238     public static boolean macEquals(
239             InputStream is
240             , StringBuffer JavaDoc mac
241             , SafeObject keybytes
242             , int buffersize
243             ) throws CryptoException {
244
245         KeyParameter key = null;
246
247         try {
248             // use the keybytes to create a key
249
key = new KeyParameter(keybytes.getBytes());
250
251             BlockCipher cipher = new AESLightEngine();
252             CBCBlockCipherMac cbcmac = new CBCBlockCipherMac(cipher);
253
254             // read the IV from the MAC
255
byte[] iv = new byte[cipher.getBlockSize()];
256             byte[] decodedMac = new byte[cbcmac.getMacSize() + iv.length];
257             decodedMac = Base64.decode(new String JavaDoc(mac));
258
259             System.arraycopy(decodedMac, 0, iv, 0, iv.length);
260
261             // use the IV and key to create cipherparameters
262
ParametersWithIV ivparam = new ParametersWithIV(key, iv);
263
264             cbcmac.init(ivparam);
265
266             byte[] result = new byte[cbcmac.getMacSize() + iv.length];
267             byte[] buffer = new byte[buffersize];
268             int length = 0;
269
270             // write the IV
271
System.arraycopy(iv, 0, result, 0, iv.length);
272
273             // read bytes into buffer and feed these bytes into MAC object
274
while ((length = is.read(buffer)) != -1) {
275                 cbcmac.update(buffer, 0, length);
276             }
277
278             cbcmac.doFinal(result, iv.length);
279
280             String JavaDoc rs = new String JavaDoc(Base64.encode(result));
281
282             if (rs.equals(mac.toString())) {
283                 return true;
284             } else {
285                 return false;
286             }
287         } catch (Exception JavaDoc ex) {
288             ex.printStackTrace();
289             throw new CryptoException(ex.getMessage());
290         } finally {
291             // clean sensitive information from memory
292
key = null;
293         }
294     }
295 }
296
Popular Tags