· 5 years ago · Oct 12, 2020, 08:56 AM
1/*
2 * To change this license header, choose License Headers in Project Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6package sk.odros.fei.upb;
7
8import java.io.File;
9import java.io.IOException;
10import java.security.SecureRandom;
11import java.util.Scanner;
12import java.util.Arrays;
13import java.io.FileInputStream;
14import java.io.FileOutputStream;
15import java.io.InputStream;
16import java.io.OutputStream;
17import java.nio.charset.StandardCharsets;
18
19import javax.crypto.Cipher;
20import javax.crypto.KeyGenerator;
21import javax.crypto.SecretKey;
22import javax.crypto.spec.IvParameterSpec;
23import javax.crypto.spec.SecretKeySpec;
24import javax.xml.bind.DatatypeConverter;
25import org.apache.commons.cli.CommandLine;
26import org.apache.commons.cli.CommandLineParser;
27import org.apache.commons.cli.DefaultParser;
28import org.apache.commons.cli.HelpFormatter;
29import org.apache.commons.cli.Option;
30import org.apache.commons.cli.Options;
31import org.apache.commons.cli.ParseException;
32import org.apache.commons.io.FileUtils;
33
34/**
35 *
36 * @author ondro
37 */
38public class MyCrypto {
39
40 public static SecretKey createKey() throws Exception {
41 SecureRandom securerandom = new SecureRandom();
42 KeyGenerator keygenerator = KeyGenerator.getInstance("AES");
43 keygenerator.init(256, securerandom);
44 SecretKey key = keygenerator.generateKey();
45 return key;
46 }
47
48 public static byte[] createInitializationVector() {
49 byte[] initializationVector = new byte[16];
50 SecureRandom secureRandom = new SecureRandom();
51 secureRandom.nextBytes(initializationVector);
52 return initializationVector;
53 }
54
55 public static byte[] encrypt(byte[] file, SecretKey secretKey, boolean fin) throws Exception {
56 Cipher cipher = Cipher.getInstance("AES");
57 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
58 if (!fin) {
59 return cipher.update(file);
60 } else {
61 return cipher.doFinal(file);
62 }
63 }
64
65 public static byte[] decrypt(byte[] cipherText, SecretKey secretKey, boolean fin) throws Exception {
66 Cipher cipher = Cipher.getInstance("AES");
67 cipher.init(Cipher.DECRYPT_MODE, secretKey);
68 byte[] result;
69 if (!fin) {
70 result = cipher.update(cipherText);
71 } else {
72 result = cipher.doFinal(cipherText);
73 }
74 return result;
75 }
76
77 public static void main(String args[]) throws Exception {
78
79 SecretKey Symmetrickey = null;
80 boolean isK = false;
81 String mode = null;
82 String filePath = null;
83 String keyPath = null;
84 String dirPath = null;
85
86 Options options = new Options();
87 options.addOption(Option.builder("f")
88 .longOpt("file")
89 .hasArg(true)
90 .desc("path to file ([REQUIRED] or use --file)")
91 .required(true)
92 .build());
93 options.addOption(Option.builder("m")
94 .longOpt("mode")
95 .hasArg(true)
96 .desc("mode ([REQUIRED] or use --mode) values [encrypt, decrypt]")
97 .required(true)
98 .build());
99 options.addOption(Option.builder("k")
100 .longOpt("key")
101 .hasArg(true)
102 .desc("Key path needed with decrypt mode")
103 .build());
104 options.addOption(Option.builder("d")
105 .longOpt("dir")
106 .hasArg(true)
107 .desc("dir path where key and encrypted file will be stored")
108 .build());
109
110 CommandLineParser parser = new DefaultParser();
111 CommandLine cmd = null;
112
113 try {
114 cmd = parser.parse(options, args);
115
116 if (cmd.hasOption("f")) {
117 filePath = cmd.getOptionValue("f");
118 }
119 if (cmd.hasOption("m")) {
120 mode = cmd.getOptionValue("m");
121 }
122 if (cmd.hasOption("k")) {
123 keyPath = cmd.getOptionValue("k");
124 isK = true;
125 }
126 if (cmd.hasOption("d")) {
127 dirPath = cmd.getOptionValue("d");
128 }
129
130 } catch (ParseException pe) {
131 System.out.println("Error parsing command-line arguments!");
132 System.out.println("Please, follow the instructions below:");
133 HelpFormatter formatter = new HelpFormatter();
134 formatter.printHelp("Log messages to sequence diagrams converter", options);
135 System.exit(1);
136 }
137
138 if (mode.equals("encrypt")) {
139 if (keyPath == null || keyPath.isEmpty()) {
140 Symmetrickey = createKey();
141 } else {
142 byte b[] = new byte[32];
143 try {
144 InputStream is = new FileInputStream(keyPath);
145 is.read(b);
146 } catch (IOException ioe) {
147 System.out.println("Invalid key path " + keyPath + " ending ...");
148 System.exit(1);
149 }
150 Symmetrickey = new SecretKeySpec(b, "AES");
151 }
152 if (dirPath == null || dirPath.isEmpty()) {
153 dirPath = new File(filePath).getParent() + "/output";
154 }
155 File f = new File(dirPath);
156 f.mkdirs();
157
158 try {
159 byte[] b = new byte[2048];
160 InputStream is = new FileInputStream(filePath);
161 OutputStream os = new FileOutputStream(new File(dirPath + "/" + new File(filePath).getName()));
162
163 int readBytes = 0;
164
165 while ((readBytes = is.read(b)) != -1) {
166 System.out.println("" + new String(b, StandardCharsets.UTF_8));
167 os.write(encrypt(b, Symmetrickey, false));
168 }
169 //os.write(encrypt(b, Symmetrickey,true));
170 is.close();
171 os.close();
172 if (!isK) {
173 OutputStream osK = new FileOutputStream(dirPath + "/key");
174 osK.write(Symmetrickey.getEncoded());
175 osK.close();
176 //System.out.println(""+DatatypeConverter.printHexBinary(Symmetrickey.getEncoded()) + " " +Symmetrickey.getEncoded().length );
177
178 }
179
180 } catch (IOException ioe) {
181 System.out.println("Error " + ioe.getMessage());
182 throw ioe;
183 }
184
185 } else if (mode.equals("decrypt")) {
186 if (!isK) {
187 System.out.println("Decrypt mode without key path. Ending ... ");
188 System.exit(1);
189 }
190 byte b[] = new byte[32];
191 try {
192 InputStream is = new FileInputStream(keyPath);
193 is.read(b);
194 } catch (IOException ioe) {
195 System.out.println("Invalid key path " + keyPath + " ending ...");
196 System.exit(1);
197 }
198 System.out.println("" + b.length);
199 Symmetrickey = new SecretKeySpec(b, 0, b.length, "AES");
200
201 System.out.println("The Symmetric Key is :" + DatatypeConverter.printHexBinary(Symmetrickey.getEncoded()));
202
203 if (dirPath == null || dirPath.isEmpty()) {
204 dirPath = new File(filePath).getParent() + "/output";
205 }
206 File f = new File(dirPath);
207 f.mkdirs();
208
209 try {
210 b = new byte[2048];
211 InputStream is = new FileInputStream(filePath);
212 OutputStream os = new FileOutputStream(dirPath + "/" + new File(filePath).getName());
213
214 int readBytes = 0;
215
216 while ((readBytes = is.read(b)) != -1) {
217 System.out.println("" + new String(b));
218 os.write(decrypt(b, Symmetrickey, false));
219 }
220 //os.write(decrypt(b, Symmetrickey,false));
221 is.close();
222 os.close();
223
224 } catch (IOException ioe) {
225 System.out.println("Error " + ioe.getMessage());
226 }
227
228 } else {
229 System.out.println("Unknown mode \"" + mode + "\" ending ...");
230 System.exit(1);
231 }
232 }
233}
234