· 6 years ago · Apr 16, 2019, 04:56 AM
1import java.io.File;
2import java.io.FileInputStream;
3import java.io.FileOutputStream;
4import java.io.IOException;
5import java.security.InvalidKeyException;
6import java.security.Key;
7import java.security.NoSuchAlgorithmException;
8
9import javax.crypto.BadPaddingException;
10import javax.crypto.Cipher;
11import javax.crypto.IllegalBlockSizeException;
12import javax.crypto.NoSuchPaddingException;
13import javax.crypto.spec.SecretKeySpec;
14
15public class Crypto {
16
17 static void fileProcessor(int cipherMode,String key,File inputFile,File outputFile){
18 try {
19 Key secretKey = new SecretKeySpec(key.getBytes(), "AES");
20 Cipher cipher = Cipher.getInstance("AES");
21 cipher.init(cipherMode, secretKey);
22
23 FileInputStream inputStream = new FileInputStream(inputFile);
24 byte[] inputBytes = new byte[(int) inputFile.length()];
25 inputStream.read(inputBytes);
26
27 byte[] outputBytes = cipher.doFinal(inputBytes);
28
29 FileOutputStream outputStream = new FileOutputStream(outputFile);
30 outputStream.write(outputBytes);
31
32 inputStream.close();
33 outputStream.close();
34
35 } catch (NoSuchPaddingException | NoSuchAlgorithmException
36 | InvalidKeyException | BadPaddingException
37 | IllegalBlockSizeException | IOException e) {
38 e.printStackTrace();
39 }
40 }
41
42 public static void main(String[] args) {
43 String key = "This is a secret";
44 File inputFile = new File("text.txt");
45 File encryptedFile = new File("text.encrypted");
46 File decryptedFile = new File("decrypted-text.txt");
47
48 try {
49 Crypto.fileProcessor(Cipher.ENCRYPT_MODE,key,inputFile,encryptedFile);
50 Crypto.fileProcessor(Cipher.DECRYPT_MODE,key,encryptedFile,decryptedFile);
51 System.out.println("Sucess");
52 } catch (Exception ex) {
53 System.out.println(ex.getMessage());
54 ex.printStackTrace();
55 }
56 }
57
58}