· 6 years ago · Oct 13, 2019, 06:50 PM
1 public boolean encryptFile(String path, String outputPath) {
2 return doStuff(path, outputPath, key, Cipher.ENCRYPT_MODE);
3 }
4
5 private static boolean doStuff(String pathIn, String pathOut, SecretKey key, int mode) {
6
7 FileInputStream in;
8 FileOutputStream out;
9
10 try {
11 in = new FileInputStream(pathIn);
12 out = new FileOutputStream(pathOut);
13
14 } catch (FileNotFoundException e) {
15 return false;
16 }
17
18 Cipher c = getCipher(key, mode);
19 return c != null && writeToFile(in, new CipherOutputStream(out, c));
20 }
21
22 private static boolean writeToFile(InputStream in, OutputStream out) {
23
24 byte[] buffer = new byte[2048];
25 int read_bytes;
26
27 while (true) {
28 try {
29 if ((read_bytes = in.read(buffer)) == -1) break;
30 out.write(buffer, 0, read_bytes);
31 } catch (IOException e) {
32 return false;
33 }
34 }
35
36 try {
37 in.close();
38 out.close();
39 } catch (IOException ignored) {}
40
41 return true;
42 }
43
44 private static Cipher getCipher(SecretKey key, int mode) {
45
46 try {
47 Cipher c = Cipher.getInstance(ALGO);
48 c.init(mode, key);
49 return c;
50 } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) {
51 return null;
52 }
53 }