· 7 years ago · Aug 17, 2018, 09:28 PM
1import java.io.*;
2import java.security.*;
3import javax.crypto.*;
4import javax.crypto.spec.*;
5
6
7public class lab1 {
8
9 private static boolean encrypt;
10
11 public static void main(String[] args) throws Exception {
12 // Check arguments to validate usage
13 if ((args.length != 1) ||
14 ((!args[0].toLowerCase().equals("encrypt")) && (!args[0].toLowerCase().equals("decrypt")))) {
15 System.err.println("Program should be ran with encrypt or decrypt as an argument");
16 return;
17 }
18
19 if (args[0].toLowerCase().equals("encrypt")) { // Decide if encrypting or decrypting
20 encrypt = true;
21 } else {
22 encrypt = false;
23 }
24
25 Console cons;
26 if ((cons = System.console()) == null) {
27 System.err.println("Couldn't get console.");
28 return;
29 }
30
31 String fileName;
32 try {
33 fileName = cons.readLine("%s", "File name: ");
34 } catch (IOError e) {
35 System.err.println("IOError: " + e.getMessage());
36 return;
37 }
38
39 char[] passwd;
40 passwd = cons.readPassword("%s", "Password: ");
41 if (passwd == null) {
42 System.err.println("Password was null, exiting!");
43 return;
44 }
45
46 crypto(fileName, passwd);
47
48 java.util.Arrays.fill(passwd, ' '); // Clear password
49 return ;
50 }
51
52 /**
53 * Takes a file name and a password and encrypts it using the password.
54 */
55 private static void crypto(String fileName, char[] passwd) throws IOException, FileNotFoundException {
56 byte[] hashValue = {(byte)0};
57
58 try {
59 hashValue = hash(passwd); // Generate the hash
60 byte[] bytes = fileToBytes(fileName); // Get the data
61 Cipher cipher = Cipher.getInstance("AES");
62
63 if (encrypt) {
64 cipher.init(Cipher.ENCRYPT_MODE, bytesToKey(hashValue));
65 } else {
66 cipher.init(Cipher.DECRYPT_MODE, bytesToKey(hashValue));
67 }
68
69 byte[] temp = cipher.doFinal(bytes); // Generate ciphertext / plaintext
70 bytesToFile(fileName, temp); // Write data
71
72 } catch (NoSuchAlgorithmException e) {
73 System.err.println("NoSuchAlgorithmException: " + e.getMessage());
74 return;
75 } catch (UnsupportedEncodingException e) {
76 System.err.println("UnsupportedEncodingException: " + e.getMessage());
77 return;
78 } catch (NoSuchPaddingException e) {
79 System.err.println("NoSuchPaddingException: " + e.getMessage());
80 } catch (InvalidKeyException e) {
81 System.err.println("InvalidKeyException: " + e.getMessage());
82 } catch (IllegalBlockSizeException e) {
83 System.err.println("IllegalBlockSizeException: " + e.getMessage());
84 } catch (BadPaddingException e) {
85 System.err.println("BadPaddingException: " + e.getMessage());
86 }
87
88 java.util.Arrays.fill(hashValue, (byte)0); // Clear hash
89 return;
90 }
91
92 /**
93 * Takes a password and hashes it using SHA-256, then returns it as a byte array.
94 */
95 private static byte[] hash(char[] passwd) throws NoSuchAlgorithmException, UnsupportedEncodingException {
96 MessageDigest digest = MessageDigest.getInstance("SHA-256");
97 digest.reset();
98 //String temp = new String(passwd);
99 //byte[] hashValue = digest.digest(temp.getBytes("UTF-16"));
100 byte[] temp = new byte[passwd.length * 2];
101 java.nio.ByteBuffer.wrap(temp).asCharBuffer().put(passwd);
102 byte[] hashValue = digest.digest(temp);
103 return hashValue;
104 }
105
106 /**
107 * Takes a file and reads it into an array of bytes.
108 */
109 private static byte[] fileToBytes(String fileName) throws FileNotFoundException, IOException {
110 File file = new File(fileName);
111 InputStream is = new FileInputStream(file);
112
113 long length = file.length();
114 if (length > Integer.MAX_VALUE) {
115 System.err.println("File too large!");
116 }
117
118 byte[] bytes = new byte[(int)length];
119 is.read(bytes);
120
121 is.close();
122 return bytes;
123 }
124
125 /**
126 * Takes an array of bytes and a filename, and overwrites the file with the bytes.
127 */
128 private static void bytesToFile(String fileName, byte[] bytes) throws FileNotFoundException, IOException {
129 File file = new File(fileName);
130 OutputStream os = new FileOutputStream(file, false);
131 os.write(bytes);
132 os.close();
133 }
134
135 /**
136 * Takes an array of bytes and creates a key from it,
137 * The array of bytes should already meet the requirements for an AES key.
138 */
139 private static SecretKey bytesToKey(byte[] bytes) {
140 SecretKeySpec key = null;
141 key = new SecretKeySpec(bytes, "AES");
142 return key;
143 }
144
145}