KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > tools > ReadJEF


1 //
2
// ____.
3
// __/\ ______| |__/\. _______
4
// __ .____| | \ | +----+ \
5
// _______| /--| | | - \ _ | : - \_________
6
// \\______: :---| : : | : | \________>
7
// |__\---\_____________:______: :____|____:_____\
8
// /_____|
9
//
10
// . . . i n j a h i a w e t r u s t . . .
11
//
12
//
13
// 08.06.2001 NK faster by using buffer of bytes to read data
14
// 29.06.2001 NK added option -e to force extract.
15
//
16
//
17
package org.jahia.tools;
18
19 import java.io.ByteArrayInputStream JavaDoc;
20 import java.io.ByteArrayOutputStream JavaDoc;
21 import java.io.DataInputStream JavaDoc;
22 import java.io.File JavaDoc;
23 import java.io.FileInputStream JavaDoc;
24 import java.io.FileNotFoundException JavaDoc;
25 import java.io.FileOutputStream JavaDoc;
26 import java.io.IOException JavaDoc;
27 import java.security.Key JavaDoc;
28 import java.security.Security JavaDoc;
29 import java.util.zip.CRC32 JavaDoc;
30
31 import javax.crypto.Cipher;
32 import javax.crypto.SecretKeyFactory;
33 import javax.crypto.spec.DESKeySpec;
34
35
36 /**
37  * Used to read data in a jef file without extracting it.
38  *
39  * @version 1.0
40  */

41 public class ReadJEF
42 {
43
44     /** the help option **/
45     private static final String JavaDoc HELP_OPTION = "-help";
46
47     private static final String JavaDoc CHAR_ENC = "UTF-16";
48
49     /** the extract option **/
50     private static final String JavaDoc EXTRACT_OPTION = "-e";
51
52     //-------------------------------------------------------------------------
53
public static void main (String JavaDoc args[])
54     {
55         System.out.println ("\nJahia Encrypted File Reader, version 1.0");
56         System.out.println ("(C) Jahia Ltd 2002\n\n");
57
58         // The source file
59
String JavaDoc srcFileName = "";
60
61         // by default, do not extract, just read
62
boolean extract = false;
63         
64         /**
65          * Retrieve command line arguments
66          */

67
68         // if no parameters are specified, display the tool usage.
69
if ( (args.length==0) || (args.length > 0) && (HELP_OPTION.equals (args[0]))) {
70             DisplayHelp ();
71             return;
72         }
73
74         // parse the parameters
75
int index = 0;
76
77         while ( (args[index]).startsWith("-") ){
78             
79             // GET THE EXTRACT OPTION
80
if (EXTRACT_OPTION.equals (args[index]))
81             {
82                 index++;
83                 extract = true;
84
85             // ALL OTHER OPTION ARE ERRORS :o)
86
} else {
87                 System.out.println ("Error: ["+args[index]+"] is not a valid option.\n");
88                 return;
89             }
90         }
91         
92         // GET THE FILE NAME
93
srcFileName = args[index];
94         
95         // check if the file exists or not
96
File JavaDoc srcFile = new File JavaDoc(srcFileName);
97         if ( !fileExists(srcFile.getAbsolutePath()) ){
98             System.out.println ("Error: Source file "+srcFileName+
99                                 " not found !");
100             return;
101         }
102
103
104         try {
105
106
107             /**
108              * Decrypt data
109              */

110
111             FileInputStream JavaDoc fstream = new FileInputStream JavaDoc (srcFile);
112             DataInputStream JavaDoc stream = new DataInputStream JavaDoc (fstream);
113
114             // create the raw byte stream from the file size by removing the
115
// CRC32 checksum bytes ( long = 8 bytes ) ,the offset ( int = 4 bytes )
116
// and the Cipher secret key ( int = 4 bytes )
117
int streamSize = (new Long JavaDoc(srcFile.length() - 16)).intValue();
118             ByteArrayOutputStream JavaDoc bos = new ByteArrayOutputStream JavaDoc();
119             byte[] buff = null;
120             int crcOffset = stream.readInt ();
121
122             System.out.println (" offset " + crcOffset);
123             
124             // read the first part of data
125
buff = new byte[crcOffset];
126             stream.read(buff,0,crcOffset);
127             bos.write(buff);
128
129             // int the Cipher
130
Security.addProvider(
131                new com.sun.crypto.provider.SunJCE());
132
133
134             // get the secret key
135
int keyLength = stream.readInt();
136             byte[] keyAsBytes = new byte[keyLength];
137             System.out.println("key length=" + keyLength);
138             stream.read(keyAsBytes);
139
140             DESKeySpec keySpec = new DESKeySpec(keyAsBytes);
141
142             Key JavaDoc myKey = SecretKeyFactory.getInstance("DES").generateSecret(keySpec);
143             keyAsBytes = myKey.getEncoded();
144             System.out.println (" Cipher secret key = "+ new String JavaDoc(keyAsBytes) );
145             
146             Cipher decCipher = Cipher.getInstance("DES");
147
148
149             decCipher.init(Cipher.DECRYPT_MODE, myKey);
150             
151             long storedChecksum = stream.readLong ();
152             System.out.println (" stored checksum = "+Long.toHexString (storedChecksum));
153
154             // read the remaining part of data
155
buff = new byte[streamSize-(crcOffset+keyLength)];
156             stream.read(buff,0,buff.length);
157             bos.write(buff);
158             
159             byte[] bytes = bos.toByteArray();
160
161             // free memory of unused objects
162
fstream.close();
163             stream = null;
164             fstream = null;
165             srcFile = null;
166             bos.close();
167             bos = null;
168             
169             
170             //DisplayBytes (bytes);
171

172             // compute the stream CRC
173
CRC32 JavaDoc crc = new CRC32 JavaDoc();
174             crc.update (bytes);
175
176             long streamChecksum = crc.getValue ();
177             System.out.println (" stream checksum = "+Long.toHexString (streamChecksum)+ "\n");
178             
179             crc = null;
180             
181             System.out.println(" data stream length before Cipher decryption " + bytes.length );
182             
183             byte[] decryptedBytes = decCipher.doFinal(bytes);
184             bytes = null;
185
186             System.out.println(" data stream length after Cipher decryption " + decryptedBytes.length );
187
188             ByteArrayInputStream JavaDoc byteStream = new ByteArrayInputStream JavaDoc (decryptedBytes);
189             stream = new DataInputStream JavaDoc (byteStream);
190             short offset = 0;
191
192             System.out.println (" Jahia Encrypted File Info :");
193
194             byte[] stringAsBytes = null;
195             
196             // extract keys value
197
offset = stream.readShort ();
198             //System.out.println ("keys nb char: " + offset);
199

200             if ( offset>0 ){
201                 stringAsBytes = new byte[offset];
202                 stream.read(stringAsBytes);
203                 String JavaDoc keys = new String JavaDoc(stringAsBytes,CHAR_ENC);
204                 System.out.println (" keys : " + keys + "\n");
205             } else {
206                 System.out.println (" no keys values\n");
207             }
208                 
209             //Extract the file content
210
byte[] data = new byte[decryptedBytes.length-(offset+2)];
211             
212             stream.read(data,0,data.length);
213
214             // extract the encrypted files
215
byteStream = new ByteArrayInputStream JavaDoc (data);
216             stream = new DataInputStream JavaDoc (byteStream);
217
218             
219             int nbBytes = data.length;
220
221             //System.out.println(" files total bytes " + nbBytes + "\n");
222

223             int nbBytesRead = 0;
224             offset = 0;
225             String JavaDoc fileName = "";
226             Long JavaDoc fSize = null;
227             byte[] aFile = null;
228                         
229             while( nbBytesRead<nbBytes ){
230                 
231                 
232                 // extract the filename
233
offset = stream.readShort();
234                 nbBytesRead += 2;
235
236                 stringAsBytes = new byte[offset];
237                 stream.read(stringAsBytes);
238                 fileName = new String JavaDoc(stringAsBytes,CHAR_ENC);
239                 nbBytesRead += offset;
240                 if ( !extract ){
241                     System.out.println(" read encrypted file " + fileName);
242                 } else {
243                     System.out.println(" extract encrypted file " + fileName);
244                 }
245                                         
246                 // extract the file size
247
fSize = new Long JavaDoc(stream.readLong());
248                 aFile = new byte[fSize.intValue()];
249                 
250                 nbBytesRead += 8;
251                 
252                 stream.read(aFile,0,fSize.intValue());
253                 nbBytesRead += fSize.intValue();
254
255                 if ( extract ){
256                     // write out the original file.
257
try {
258                         
259                         FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc (fileName);
260             
261                         fos.write (aFile);
262             
263                         // flush the stream into the file and close the file
264
fos.flush();
265                         fos.close();
266                     }
267                     catch (FileNotFoundException JavaDoc ex) {
268                         System.out.println ("ERROR : Could not create the encrypted file");
269                         return;
270                     }
271                     catch (SecurityException JavaDoc ex) {
272                         System.out.println ("ERROR : No security permissions to create the file.");
273                         return;
274                     }
275                     catch (IOException JavaDoc ex) {
276                         System.out.println ("ERROR : I/O error.");
277                         return;
278                     }
279                 }
280             }
281
282         }
283         catch (IOException JavaDoc ex) {
284             //System.out.println ("ERROR : I/O exception while reading the file.");
285
return;
286         }
287         catch (Exception JavaDoc e) {
288             System.out.println ("ERROR : " + e.getMessage());
289             return;
290         }
291
292     }
293
294
295     //-------------------------------------------------------------------------
296
private static void DisplayBytes (byte[] bytes)
297     {
298         //System.out.print (" stream = ");
299

300         for (int i=0; i<bytes.length; i++) {
301             //System.out.print (bytes[i]+" ");
302
}
303
304         //System.out.print("\n");
305
}
306
307
308     //-------------------------------------------------------------------------
309
private static void DisplayHelp ()
310     {
311         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc ();
312
313         buffer.append (" usage : ReadEPF [options] myfile\n\n");
314         buffer.append (" options :\n");
315
316         buffer.append (" "+EXTRACT_OPTION+"\n"+
317                        " read and extract \n"+
318                        " default[read only]\n");
319         buffer.append (" source file \n"+
320                        " the source file name)\n");
321
322         buffer.append ("\n\n");
323
324         System.out.println (buffer.toString());
325     }
326
327
328     //-------------------------------------------------------------------------
329
/**
330      * check if a file or directory exists. The check is case sensitive
331      *
332      * @author NK
333      * @param String the absolute path
334      * @return boolean true if comparison is success
335      */

336     private static boolean fileExists(String JavaDoc path){
337         
338         File JavaDoc tmpFile = new File JavaDoc(path);
339         if ( tmpFile != null && tmpFile.isFile() ){
340             String JavaDoc name = tmpFile.getName();
341             if ( tmpFile.getParentFile() != null ){
342                 File JavaDoc[] files = tmpFile.getParentFile().listFiles();
343                 int nbFiles = files.length;
344                 for (int i=0 ; i<nbFiles ; i++){
345                     if ( files[i].getName().equals(name) ){
346                         return true;
347                     }
348                 }
349             }
350         }
351         return false;
352     }
353
354 }
355
Popular Tags