· 6 years ago · Oct 09, 2019, 06:08 PM
1package sample;
2
3import javax.crypto.*;
4import java.io.*;
5import java.security.InvalidKeyException;
6import java.security.NoSuchAlgorithmException;
7
8public class CypherUtils {
9
10 private static final String ALGO = "DESede";
11 private SecretKey key;
12
13 public CypherUtils() {
14 key = generateKey();
15 }
16
17 public boolean encrypt(String path, String outputPath) {
18 return doStuff(path, outputPath, key, Cipher.ENCRYPT_MODE);
19 }
20
21 public boolean decrypt(String path, String outputPath) {
22 return doStuff(path, outputPath, key, Cipher.DECRYPT_MODE);
23 }
24
25 private static boolean doStuff(String pathIn, String pathOut, SecretKey key, int mode) {
26
27 FileInputStream in;
28 FileOutputStream out;
29
30 try {
31 in = new FileInputStream(pathIn);
32 out = new FileOutputStream(pathOut);
33
34 } catch (FileNotFoundException e) {
35 return false;
36 }
37
38 Cipher c = getCipher(key, mode);
39 return c != null && writeToFile(in, new CipherOutputStream(out, c));
40 }
41
42 private static boolean writeToFile(InputStream in, OutputStream out) {
43
44 byte[] buffer = new byte[2048];
45 int read_bytes;
46
47 while (true) {
48 try {
49 if ((read_bytes = in.read(buffer)) == -1) break;
50 out.write(buffer, 0, read_bytes);
51 } catch (IOException e) {
52 return false;
53 }
54 }
55
56 try {
57 in.close();
58 out.close();
59 } catch (IOException ignored) {}
60
61 return true;
62 }
63
64 private static SecretKey generateKey() {
65 try {
66 KeyGenerator keygen = KeyGenerator.getInstance(ALGO);
67 return keygen.generateKey();
68 } catch (NoSuchAlgorithmException e) {
69 e.printStackTrace();
70 }
71 return null;
72 }
73
74 private static Cipher getCipher(SecretKey key, int mode) {
75
76 try {
77 Cipher c = Cipher.getInstance(ALGO);
78 c.init(mode, key);
79 return c;
80 } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) {
81 return null;
82 }
83 }
84}