· 8 years ago · Jan 30, 2018, 04:38 AM
1// package Encryption;
2
3 import java.io.BufferedInputStream;
4 import java.io.BufferedOutputStream;
5 import java.io.File;
6 import java.io.FileInputStream;
7 import java.io.FileNotFoundException;
8 import java.io.FileOutputStream;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.OutputStream;
12 import java.nio.ByteBuffer;
13 import java.security.AlgorithmParameters;
14 import java.security.MessageDigest;
15 import java.security.SecureRandom;
16 import java.util.Arrays;
17
18
19 import javax.crypto.BadPaddingException;
20 import javax.crypto.Cipher;
21 import javax.crypto.IllegalBlockSizeException;
22 import javax.crypto.SecretKey;
23 import javax.crypto.SecretKeyFactory;
24 import javax.crypto.spec.IvParameterSpec;
25 import javax.crypto.spec.PBEKeySpec;
26 import javax.crypto.spec.SecretKeySpec;
27
28
29 public class Encryption {
30 static final String INPUT_FILE_NAME = "c:\\test\\test.exe";
31 static final String ENCRYPTED_3DES_FILE_NAME = "c:\\test\\test3des.bin";
32 static final String EXECUTABLE_3DES_FILE_NAME = "c:\\test\\test3des.exe";
33 static final String ENCRYPTED_3DES2_FILE_NAME = "c:\\test\\test3des2.bin";
34 static final String EXECUTABLE_3DES2_FILE_NAME = "c:\\test\\test3des2.exe";
35 static final String ENCRYPTED_AES128_FILE_NAME = "c:\\test\\testaes128.bin";
36 static final String EXECUTABLE_AES128_FILE_NAME = "c:\\test\\testaes128.exe";
37 public static byte[] read(String aInputFileName){
38 //log("Reading in binary file named : " + aInputFileName);
39 File file = new File(aInputFileName);
40 //log("File size: " + file.length());
41 byte[] result = new byte[(int)file.length()];
42 try {
43 InputStream input = null;
44 try {
45 int totalBytesRead = 0;
46 input = new BufferedInputStream(new FileInputStream(file));
47 while(totalBytesRead < result.length){
48 int bytesRemaining = result.length - totalBytesRead;
49 //input.read() returns -1, 0, or more :
50 int bytesRead = input.read(result, totalBytesRead, bytesRemaining);
51 if (bytesRead > 0){
52 totalBytesRead = totalBytesRead + bytesRead;
53 }
54 }
55 /*
56 the above style is a bit tricky: it places bytes into the 'result' array;
57 'result' is an output parameter;
58 the while loop usually has a single iteration only.
59 */
60 //log("Num bytes read: " + totalBytesRead);
61 }
62 finally {
63 //log("Closing input stream.");
64 input.close();
65 }
66 }
67 catch (FileNotFoundException ex) {
68 log("File not found.");
69 }
70 catch (IOException ex) {
71 //log(ex);
72 }
73 return result;
74 }
75 static public void PrepareInput() throws Exception
76 {
77 //read in the bytes
78 byte[] text;
79 byte[] codedtext;
80
81 /* Create Input file for 3DES algorithm */
82 text = Encryption.read(INPUT_FILE_NAME);
83 codedtext = new Encryption().encrypt3Des2(text);
84 //write it back out to a different file name
85 write(codedtext, ENCRYPTED_3DES2_FILE_NAME);
86
87 /* Create Input file for AES128 algorithm */
88 text = null;
89 codedtext = null;
90 text = Encryption.read(INPUT_FILE_NAME);
91 codedtext = new Encryption().encryptAes128(text);
92 //write it back out to a different file name
93 write(codedtext, ENCRYPTED_AES128_FILE_NAME);
94
95 }
96
97 static public void PerformTest() throws Exception
98 {
99 Process process;
100 long time1, time2;
101 long millis, seconds, minutes, hours, days;
102 byte[] codedtext, decodedtext;
103
104 Runtime runtime = Runtime.getRuntime();
105 // Execute the input program without encryption and decryption
106 /***********************************************************************************/
107 System.out.println("\nAlgorithm 1. No Encryption and DEcryption " + INPUT_FILE_NAME);
108 time1 = System.currentTimeMillis();
109
110 try {
111 System.out.println("\nStarting the process " + INPUT_FILE_NAME);
112 process = runtime.exec(INPUT_FILE_NAME);
113 System.out.println("\nWaiting for the process " + INPUT_FILE_NAME + " to finish");
114 process.getInputStream();
115 process.waitFor();
116 System.out.println("\nthe process finished..");
117
118 }
119 catch (IOException e) {
120 e.printStackTrace();
121 }
122
123 time2 = System.currentTimeMillis();
124 time2 -= time1;
125
126 seconds = time2/1000;
127 millis = time2%1000;
128 minutes = seconds/60;
129 seconds %= 60;
130 hours = minutes/60;
131 minutes %= 60;
132 days = hours/24;
133 hours %= 24;
134
135 System.out.println(INPUT_FILE_NAME + "execution time: " + days + "days " + hours + " hours " + minutes +
136 " minutes " + seconds + " seconds " + millis +" millis");
137
138
139 /***********************************************************************************/
140 /* Algorith 3DES */
141 /***********************************************************************************/
142 System.out.println("\nAlgorithm 2. Encryption and DEcryption with 3DES " + INPUT_FILE_NAME);
143 System.out.println("Starting Timer..");
144 System.out.println("Starting decoding..");
145 codedtext = null;
146 //Start timer. Test Starts
147 time1 = System.currentTimeMillis();
148 codedtext = Encryption.read(ENCRYPTED_3DES2_FILE_NAME);
149 decodedtext = new Encryption().decrypt3Des2(codedtext);
150
151 Encryption.write(decodedtext, EXECUTABLE_3DES2_FILE_NAME);
152 try {
153 System.out.println("\nStarting the process " + EXECUTABLE_3DES2_FILE_NAME);
154 process = runtime.exec(EXECUTABLE_3DES2_FILE_NAME);
155 System.out.println("\nWaiting for the process " + EXECUTABLE_3DES2_FILE_NAME + " to finish");
156 process.getInputStream();
157 process.waitFor();
158 System.out.println("\nthe process finished..");
159
160 }
161 catch (IOException e) {
162 e.printStackTrace();
163 }
164
165 time2 = System.currentTimeMillis();
166 time2 -= time1;
167
168 seconds = time2/1000;
169 millis = time2%1000;
170 minutes = seconds/60;
171 seconds %= 60;
172 hours = minutes/60;
173 minutes %= 60;
174 days = hours/24;
175 hours %= 24;
176
177 System.out.println(EXECUTABLE_3DES2_FILE_NAME + "execution time: " + days + "days " + hours + " hours " + minutes +
178 " minutes " + seconds + " seconds " + millis +" millis");
179 /***********************************************************************************/
180 /* Algorith AES128 */
181 /***********************************************************************************/
182 System.out.println("\nAlgorithm 3. Encryption and DEcryption with AES128 " + INPUT_FILE_NAME);
183
184 System.out.println("Starting Timer..");
185 System.out.println("Starting decoding..");
186 codedtext = null;
187 decodedtext = null;
188 time1 = System.currentTimeMillis();
189 //Start timer. Test Starts
190 //codedtext = new Encryption.read(ENCRYPTED_3DES_FILE_NAME);
191 codedtext = Encryption.read(ENCRYPTED_AES128_FILE_NAME);
192 decodedtext = new Encryption().decryptAes128(codedtext);
193
194 Encryption.write(decodedtext, EXECUTABLE_AES128_FILE_NAME);
195 try {
196 //runtime.exec("cmd /c start" + EXECUTABLE_AES256_FILE_NAME);
197 System.out.println("\nStarting the process " + EXECUTABLE_AES128_FILE_NAME);
198 process = runtime.exec(EXECUTABLE_AES128_FILE_NAME);
199 System.out.println("\nWaiting for the process " + EXECUTABLE_AES128_FILE_NAME + " to finish");
200 process.getInputStream();
201 process.waitFor();
202 System.out.println("\nThe process finished..");
203 }
204 catch (IOException e) {
205 e.printStackTrace();
206 }
207
208 //Stop timer. Test ends
209 time2 = System.currentTimeMillis();
210 time2 -= time1;
211
212 seconds = time2/1000;
213 millis = time2%1000;
214 minutes = seconds/60;
215 seconds %= 60;
216 hours = minutes/60;
217 minutes %= 60;
218 days = hours/24;
219 hours %= 24;
220
221 System.out.println(EXECUTABLE_AES128_FILE_NAME + " execution time: " + days + "days " + hours + " hours " + minutes +
222 " minutes " + seconds + " seconds " + millis +" millis");
223 //System.out.println(codedtext); // this is a byte array, you'll just see a reference to an array
224 //System.out.println(decodedtext); // This correctly shows "kyle boon"
225
226
227 }
228 public static void main(String[] args) throws Exception {
229
230 PrepareInput();
231 // Execute the input program without encryption and decryption
232 for (int i = 0; i < 3; i++) {
233 PerformTest();
234 }
235 }
236 static void log(IOException arg) {
237 }
238 static void log(String arg) {
239 System.out.println(arg);
240 }
241
242 /**
243 Write a byte array to the given file.
244 Writing binary data is significantly simpler than reading it.
245 */
246 static void write(byte[] aInput, String aOutputFileName){
247 //log("Writing binary file...");
248 try {
249 OutputStream output = null;
250 try {
251 output = new BufferedOutputStream(new FileOutputStream(aOutputFileName));
252 output.write(aInput);
253 }
254 finally {
255 output.close();
256 }
257 }
258 catch(FileNotFoundException ex){
259 log("File not found.");
260 }
261 catch(IOException ex){
262 log(ex);
263 }
264 }
265
266 public byte[] encrypt3Des(byte[] plainTextBytes) throws Exception {
267 final MessageDigest md = MessageDigest.getInstance("md5");
268 final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
269 .getBytes("utf-8"));
270 final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
271 for (int j = 0, k = 16; j < 8;) {
272 keyBytes[k++] = keyBytes[j++];
273 }
274
275 final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
276 final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
277 final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
278 cipher.init(Cipher.ENCRYPT_MODE, key, iv);
279
280 final byte[] cipherText = cipher.doFinal(plainTextBytes);
281 // final String encodedCipherText = new sun.misc.BASE64Encoder()
282 // .encode(cipherText);
283
284 return cipherText;
285 }
286
287 public byte[] decrypt3Des(byte[] message) throws Exception {
288 final MessageDigest md = MessageDigest.getInstance("md5");
289 final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
290 .getBytes("utf-8"));
291 final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
292 for (int j = 0, k = 16; j < 8;) {
293 keyBytes[k++] = keyBytes[j++];
294 }
295
296 final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
297 final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
298 final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
299 decipher.init(Cipher.DECRYPT_MODE, key, iv);
300
301 // final byte[] encData = new
302 // sun.misc.BASE64Decoder().decodeBuffer(message);
303 final byte[] plainText = decipher.doFinal(message);
304
305 return plainText;
306 }
307
308 /**********************************************************************************/
309 public byte[] encrypt3Des2(byte[] word) throws Exception {
310
311 String password="Hello";
312 /*you can give whatever you want for password. This is for testing purpose*/
313
314 SecureRandom random = new SecureRandom();
315 byte bytes[] = new byte[24];
316 random.nextBytes(bytes);
317 byte[] saltBytes = bytes;
318
319 // Derive the key
320 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
321 PBEKeySpec spec = new PBEKeySpec(password.toCharArray(),saltBytes,65556,8*3*8);
322 SecretKey secretKey = factory.generateSecret(spec);
323 SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "DESede");
324
325 //encrypting the word
326
327 Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
328 byte[] ivBytes = new byte[8];
329 random.nextBytes(ivBytes);
330 final IvParameterSpec iv = new IvParameterSpec(ivBytes);
331 cipher.init(Cipher.ENCRYPT_MODE, secret, iv);
332 byte[] encryptedTextBytes = cipher.doFinal(word);
333
334 //prepend salt and vi
335
336 byte[] buffer = new byte[saltBytes.length + ivBytes.length + encryptedTextBytes.length];
337
338 System.arraycopy(saltBytes, 0, buffer, 0, saltBytes.length);
339 System.arraycopy(ivBytes, 0, buffer, saltBytes.length, ivBytes.length);
340
341 System.arraycopy(encryptedTextBytes, 0, buffer, saltBytes.length + ivBytes.length, encryptedTextBytes.length);
342
343 //return new Base64().encodeToString(buffer);
344 return buffer;
345 }
346
347 public byte[] decrypt3Des2(byte[] encryptedText) throws Exception {
348
349 String password="Hello";
350 Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
351
352 //strip off the salt and iv
353 ByteBuffer buffer = ByteBuffer.wrap(encryptedText);
354
355 byte[] saltBytes = new byte[24];
356 buffer.get(saltBytes, 0, saltBytes.length);
357 byte[] ivBytes1 = new byte[cipher.getBlockSize()];
358 buffer.get(ivBytes1, 0, ivBytes1.length);
359 byte[] encryptedTextBytes = new byte[buffer.capacity() - saltBytes.length - ivBytes1.length];
360
361 buffer.get(encryptedTextBytes);
362
363 // Deriving the key
364
365 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
366 PBEKeySpec spec = new PBEKeySpec(password.toCharArray(),saltBytes,65556,8*3*8);
367 SecretKey secretKey = factory.generateSecret(spec);
368 SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "DESede");
369
370 cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes1));
371
372 byte[] decryptedTextBytes = null;
373
374 try {
375 decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
376 } catch (IllegalBlockSizeException e) {
377 e.printStackTrace();
378 } catch (BadPaddingException e) {
379 e.printStackTrace();
380 }
381 return decryptedTextBytes;
382 }
383
384
385
386 /**************************************************************************************/
387
388 public byte[] encryptAes128(byte[] word) throws Exception {
389
390 byte[] ivBytes;
391 String password="Hello";
392 /*you can give whatever you want for password. This is for testing purpose*/
393
394 SecureRandom random = new SecureRandom();
395 byte bytes[] = new byte[20];
396 random.nextBytes(bytes);
397 byte[] saltBytes = bytes;
398
399 // Derive the key
400 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
401
402 PBEKeySpec spec = new PBEKeySpec(password.toCharArray(),saltBytes,65556,128);
403
404 SecretKey secretKey = factory.generateSecret(spec);
405 SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
406
407 //encrypting the word
408
409 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
410 cipher.init(Cipher.ENCRYPT_MODE, secret);
411 AlgorithmParameters params = cipher.getParameters();
412 ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
413
414 byte[] encryptedTextBytes = cipher.doFinal(word);
415
416 //prepend salt and vi
417
418 byte[] buffer = new byte[saltBytes.length + ivBytes.length + encryptedTextBytes.length];
419
420 System.arraycopy(saltBytes, 0, buffer, 0, saltBytes.length);
421 System.arraycopy(ivBytes, 0, buffer, saltBytes.length, ivBytes.length);
422
423 System.arraycopy(encryptedTextBytes, 0, buffer, saltBytes.length + ivBytes.length, encryptedTextBytes.length);
424
425 //return new Base64().encodeToString(buffer);
426 return buffer;
427 }
428
429 public byte[] decryptAes128(byte[] encryptedText) throws Exception {
430
431 String password="Hello";
432 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
433
434 //strip off the salt and iv
435 ByteBuffer buffer = ByteBuffer.wrap(encryptedText);
436
437 byte[] saltBytes = new byte[20];
438 buffer.get(saltBytes, 0, saltBytes.length);
439 byte[] ivBytes1 = new byte[cipher.getBlockSize()];
440 buffer.get(ivBytes1, 0, ivBytes1.length);
441 byte[] encryptedTextBytes = new byte[buffer.capacity() - saltBytes.length - ivBytes1.length];
442
443 buffer.get(encryptedTextBytes);
444
445 // Deriving the key
446
447 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
448
449 PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), saltBytes, 65556, 128);
450
451 SecretKey secretKey = factory.generateSecret(spec);
452 SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
453
454 cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes1));
455
456 byte[] decryptedTextBytes = null;
457
458 try {
459 decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
460 } catch (IllegalBlockSizeException e) {
461 e.printStackTrace();
462 } catch (BadPaddingException e) {
463 e.printStackTrace();
464 }
465 return decryptedTextBytes;
466 }
467 }