repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

adds java tool `aes` encryptor/decryptor

7fe35d21f78cf7c25c136016f433d4ff0ff77754

Oliver Krylow <o.krylow@isp-insoft.de> ·

unsigned

Browse filesCompare with HEAD

Changed files (5)

git/.gitconfig

Modified
8 8 quotepath = false
9 9 autocrlf = input
10 10 pager = delta
11 + safecrlf = false
12 13 [diff]
13 14 colorMoved = default

tools/aes.java

Added
new file mode 100644
1 +import static java.lang.System.out;
3 +import java.nio.file.*;
4 +import java.nio.charset.*;
5 +import java.nio.*;
6 +import java.io.*;
7 +import java.util.*;
9 +import java.security.*;
10 +import java.security.spec.*;
12 +import javax.crypto.*;
13 +import javax.crypto.spec.*;
15 +class aes {
17 + enum Command { ENCRYPT, DECRYPT };
19 + static Cipher AES_GCM_PKCS5;
20 + static byte[] SALT = new byte[] { 116, 104, 101, 32, 109, 111, 111, 110, 32, 105, 115, 32, 104, 105, 100, 100, 101, 110, 32, 105, 110, 32, 112, 108, 97, 105, 110, 32, 118, 105, 101, 119 };
21 + static SecureRandom RANDOM = new SecureRandom();
22 + /*
23 + * 12 ist NIST recommendation. supposedly fast and secure enough...
24 + */
25 + static int GCM_IV_SIZE = 12;
26 + /*
27 + * AES encrypts 128-blocks internally, so this should be reasonable memory bufer size.
28 + */
29 + static int READ_BUFFER_SIZE = 128;
30 + /*
31 + * Supported sizes for GCM authentication tags seem to be {128, 120, 112, 104, 96}.
32 + * But we do not really care, since we do not use them here.
33 + */
34 + static int GCM_AUTH_TAG_SIZE = 96;
36 + public static void main(String[] arguments) throws Throwable {
37 + if(arguments.length == 0){
38 + usage();
39 + throw fail();
40 + }
42 + var input_command = arguments[0];
43 + Command command;
44 + if ("encrypt".startsWith(input_command)) { command = Command.ENCRYPT; }
45 + else if ("decrypt".startsWith(input_command)) { command = Command.DECRYPT; }
46 + else { throw fail("unknown command %s given%n", emphasize_global(input_command)); }
48 + AES_GCM_PKCS5 = Cipher.getInstance("AES/GCM/NoPadding");
50 + var console = System.console();
51 + /*
52 + * If there is no console, this program is most likely part of a pipe.
53 + * In such cases a `--password-file` flag is mandatory, because we cannot interactively ask for the password.
54 + */
55 + if(console == null){
56 + if(arguments.length != 3 || !"--password-file".equals(arguments[1])) {
57 + usage();
58 + throw fail("When running %s non-interactively, the %s flag is required.%nOtherwise there is no way to securely obtain the password.%n",emphasize_local("aes"), emphasize_global("--password-file"));
59 + }
60 + var password_file = Path.of(arguments[2]);
61 + if(!Files.exists(password_file)) { throw fail("the given password file %s does not exist%n", emphasize_local(password_file.toString())); }
62 + var password = toChars(Files.readAllBytes(password_file));
63 + switch (command) {
64 + case ENCRYPT:
65 + encrypt(password, System.in, System.out);
66 + break;
67 + case DECRYPT:
68 + decrypt(password, System.in, System.out);
69 + break;
70 + }
71 + }
72 + else {
73 + if(arguments.length <= 1) {
74 + usage();
75 + throw fail("not enough arguments given%n");
76 + }
77 + char[] password;
78 + String input;
79 + String output;
80 + if("--password-file".equals(arguments[1])) {
81 + if(arguments.length != 5) {
82 + usage();
83 + throw fail("the flag %s requires a path%n", emphasize_local("--password-file"));
84 + }
85 + var password_file = Path.of(arguments[2]);
86 + if(!Files.exists(password_file)) { throw fail("the given password file %s does not exist%n", emphasize_local(password_file.toString())); }
87 + password = toChars(Files.readAllBytes(password_file));
88 + input = arguments[3];
89 + output = arguments[4];
90 + }
91 + else {
92 + if(arguments.length != 3) {
93 + usage();
94 + throw fail("when encrypting/decrypting a file, an output path is required%n");
95 + }
96 + password = console.readPassword("[%s]:",emphasize_global("Password"));
97 + input = arguments[1];
98 + output = arguments[2];
99 + }
101 + var input_path = Path.of(input);
102 + if(!Files.exists(input_path)) { throw fail("the given input path %s does not exist%n", emphasize_global(input_path.toString())); }
103 + var output_path = Path.of(output);
104 + if(Files.exists(output_path)) { throw fail("the output path %s already exists%n", emphasize_global(output_path.toString())); }
106 + var input_stream = Files.newInputStream(input_path, StandardOpenOption.READ);
107 + var output_stream = Files.newOutputStream(output_path, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
109 + switch (command) {
110 + case ENCRYPT:
111 + encrypt(password, input_stream, output_stream);
112 + break;
113 + case DECRYPT:
114 + decrypt(password, input_stream, output_stream);
115 + break;
119 + throw exit();
122 + static void encrypt(char[] password, InputStream input, OutputStream output) throws Exception {
123 + // FIXME: generate random salt and append it here just like IV
124 + // in GCM the IV should be unique per encrypted thingy
125 + var initialization_vector = new byte[GCM_IV_SIZE];
126 + RANDOM.nextBytes(initialization_vector);
127 + //save the IV for the decryption step later. secure? nope. but how else are we to share IVs between encryption/decryption?
128 + output.write(initialization_vector);
129 + var secret = toSecretKey(password);
130 + var parameter_spec = new GCMParameterSpec(GCM_AUTH_TAG_SIZE, initialization_vector);
132 + AES_GCM_PKCS5.init(Cipher.ENCRYPT_MODE, secret, parameter_spec);
133 + var read_buffer = new byte[READ_BUFFER_SIZE];
134 + var aes_buffer = new byte[READ_BUFFER_SIZE];
135 + int read_bytes_count = 0;
136 + while((read_bytes_count = input.read(read_buffer)) != -1){
137 + var aes_bytes_count = AES_GCM_PKCS5.update(read_buffer, 0, read_bytes_count, aes_buffer);
138 + output.write(aes_buffer, 0, aes_bytes_count);
140 + output.write(AES_GCM_PKCS5.doFinal());
143 + static void decrypt(char[] password, InputStream input, OutputStream output) throws Exception {
144 + //the IV get prepended to the data during encryption
145 + var initialization_vector = new byte[GCM_IV_SIZE];
146 + input.read(initialization_vector);
147 + var parameter_spec = new GCMParameterSpec(GCM_AUTH_TAG_SIZE, initialization_vector);
148 + var secret = toSecretKey(password);
150 + AES_GCM_PKCS5.init(Cipher.DECRYPT_MODE, secret, parameter_spec);
151 + var read_buffer = new byte[READ_BUFFER_SIZE];
152 + var aes_buffer = new byte[READ_BUFFER_SIZE];
153 + int read_bytes_count = 0;
154 + while((read_bytes_count = input.read(read_buffer)) != -1){
155 + var aes_bytes_count = AES_GCM_PKCS5.update(read_buffer, 0, read_bytes_count, aes_buffer);
156 + output.write(aes_buffer, 0, aes_bytes_count);
158 + //FIXME: the java impl of GCM seems to buffer the whole data in memory and only releasing it on doFinal. yuck!
159 + //TODO: in the case of AES GCM the final byte block is the authentication tag.
160 + //as such it should porbably NOT be written to the output file.
161 + //or is this assumption wrong?
162 + output.write(AES_GCM_PKCS5.doFinal());
163 + //FIXME: when given a wrong password we get a nonsensical error. make this nicer for human
166 + static SecretKey toSecretKey(char[] password) throws Exception {
167 + var factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
168 + var spec = new PBEKeySpec(password, SALT, 65536, 256);
169 + return new SecretKeySpec(factory.generateSecret(spec).getEncoded() , "AES");
172 + static char[] toChars(byte[] bytes) {
173 + var byte_buffer = ByteBuffer.wrap(bytes);
174 + var char_buffer = StandardCharsets.UTF_8.decode(byte_buffer);
175 + return char_buffer.array();
178 + static void usage() {
179 + out.printf("%s encrypts/decrypts data.%n", emphasize_local("Symmetrically "));
180 + out.printf("%s: java aes.java <e(ncrypt)|d(ecrypt)> [--password-file <path>] <input path> <output path>%n", emphasize_global("Usage for files"));
181 + out.printf("%s: java aes.java <e(ncrypt)|d(ecrypt)> --password-file <path>%n", emphasize_global("Usage for stdin/stdout"));
184 + static Throwable exit() {
185 + out.printf("%s!%n", emphasize_local("Done"));
186 + System.exit(0);
187 + //abuse control flow to make compiler realize `exit` will never return
188 + return new Throwable();
191 + static String emphasize_global(String message) {
192 + return "\033[4m" + message + "\033[0m";
195 + static String emphasize_local(String message) {
196 + return "\033[3m" + message + "\033[0m";
199 + static Throwable fail(String message, Object... arguments) {
200 + out.printf(message, arguments);
201 + System.exit(-1);
202 + //abuse control flow to make compiler realize `exit` will never return
203 + return new Throwable();
206 + static Throwable fail() {
207 + System.exit(-1);
208 + //abuse control flow to make compiler realize `exit` will never return
209 + return new Throwable();

tools/pipi.pass

Added
new file mode 100644
1 +dein arsch stinkt nach märchenfleisch

tools/probe_content.java

Deleted
deleted file mode 100644
1 -import java.nio.file.*;
2 -import java.io.*;
4 -class probe_content {
5 - public static void main(String[] command_line_arguments) throws Throwable {
6 - if (command_line_arguments.length < 1) {
7 - throw panic("Give path to file or folder to probe content types of.");
8 - }
9 - var rawPath = command_line_arguments[0];
10 - var path = Paths.get(rawPath);
11 - if (!Files.exists(path)) {
12 - throw panic("The given path '%s' does not exist.", path);
13 - }
14 - if (Files.isRegularFile(path)) {
15 - printContentType(path);
16 - } else if (Files.isDirectory(path)) {
17 - Files.list(path).forEach(probe_content::printContentType);
18 - } else {
19 - throw panic("Dafuq is the given file '%s'???", path);
20 - }
21 - }
23 - private static String probeContentType(Path path) {
24 - try{
25 - var type = Files.probeContentType(path);
26 - if(type == null) return "[unknown]";
27 - return type;
28 - }
29 - catch(IOException __){
30 - return "[unknown]";
31 - }
32 - }
34 - private static void printContentType(Path path) {
35 - var type = probeContentType(path);
36 - print("File '%s' is of type '%s'.", path.getFileName(), type);
37 - }
39 - private static void print(String message, Object... parameters) {
40 - System.out.printf("%s%n", String.format(message, parameters));
41 - }
43 - private static Throwable panic(String message, Object... parameters) {
44 - print(message, parameters);
45 - System.exit(-1);
46 - return new Throwable();
47 - }
48 -}

tools/test_aes.nu

Added
new file mode 100644
1 +rm -f aes.java.enc
2 +rm -f aes.java.dec
3 +java aes.java en --password-file pipi.pass aes.java aes.java.enc
4 +java aes.java de --password-file pipi.pass aes.java.enc aes.java.dec
6 +delta aes.java aes.java.dec