· 5 years ago · Nov 16, 2019, 08:12 AM
1package com.cottonlesergal.serialization;
2
3import javax.crypto.BadPaddingException;
4import javax.crypto.Cipher;
5import javax.crypto.IllegalBlockSizeException;
6import javax.crypto.NoSuchPaddingException;
7import javax.crypto.spec.SecretKeySpec;
8import java.io.*;
9import java.security.InvalidKeyException;
10import java.security.Key;
11import java.security.NoSuchAlgorithmException;
12
13public class FileEnDe implements java.io.Serializable{
14 private static final String ALGORITHM = "AES";
15 private static final String TRANSFORMATION = "AES";
16
17
18 private File file;
19
20 String key = "Mary has one cat";
21
22 public FileEnDe(File fileToEnDe){
23 file = fileToEnDe;
24 }
25
26 public static void encrypt(String key, File inputFile, File outputFile){
27 doCrypto(Cipher.ENCRYPT_MODE, key, inputFile, outputFile);
28 }
29
30 public static void decrypt(String key, File inputFile, File outputFile){
31 doCrypto(Cipher.DECRYPT_MODE, key, inputFile, outputFile);
32 }
33
34 private static void doCrypto(int cipherMode, String key, File inputFile,
35 File outputFile){
36 try {
37 Key secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
38 Cipher cipher = Cipher.getInstance(TRANSFORMATION);
39 cipher.init(cipherMode, secretKey);
40
41 FileInputStream inputStream = new FileInputStream(inputFile);
42 byte[] inputBytes = new byte[(int) inputFile.length()];
43 inputStream.read(inputBytes);
44
45 byte[] outputBytes = cipher.doFinal(inputBytes);
46
47 FileOutputStream outputStream = new FileOutputStream(outputFile);
48 outputStream.write(outputBytes);
49
50 inputStream.close();
51 outputStream.close();
52
53 } catch (NoSuchPaddingException | NoSuchAlgorithmException
54 | InvalidKeyException | BadPaddingException
55 | IllegalBlockSizeException | IOException e) {
56 e.printStackTrace();
57 }
58 }
59
60 public void encryptFile(){
61 File inputFile = new File(file.getAbsolutePath());
62
63 try {
64 BufferedReader br = new BufferedReader(new FileReader(inputFile));
65 String st;
66 while ((st = br.readLine()) != null)
67 System.out.println(st);
68
69 encrypt(key, inputFile, inputFile);
70
71 BufferedReader br2 = new BufferedReader(new FileReader(inputFile));
72 String str;
73 while ((str = br2.readLine()) != null)
74 System.out.println(str);
75
76 } catch (Exception e) {
77 System.out.println(e.getMessage());
78 e.printStackTrace();
79 }
80 }
81
82 public void decryptFile(){
83 File encryptedFile = new File(file.getAbsolutePath());
84
85 try {BufferedReader br = new BufferedReader(new FileReader(encryptedFile));
86 String st;
87 while ((st = br.readLine()) != null)
88 System.out.println(st);
89
90 decrypt(key, encryptedFile, encryptedFile);
91
92 BufferedReader br2 = new BufferedReader(new FileReader(encryptedFile));
93 String str;
94 while ((str = br2.readLine()) != null)
95 System.out.println(str);
96
97 } catch (Exception e) {
98 System.out.println(e.getMessage());
99 e.printStackTrace();
100 }
101 }
102}