0

I have written a program that encrypts a given jar file. Quite straight forward. Now I'm in the process of writing a second program that decrypts the file by bruteforcing it. (They are both standalone)

After encrypting a given file I end up with a byte[] containing the encrypted file data. I converted this byte[] to a String and made it output to the console so I could easily copy and paste the data.

Then I initializing a new String in the 'decrypter' and pasted this data of the encrypted file. For small files this works, but for larger files it doesn't work due to the String literal size limit. How can I hardcode this data into the decrypter?

Quick pseudo-code

Encrypter:

public byte[] encrypt(){
}
String encryptedData = Arrays.toString(encrypt(data));

Decrypter:

String encryptedData = "[-3, -66, -89, -14, 5, -72, 12, 5, ........
// note that I actually copy paste - hardcode the string
decrypt(stringToByteArray(encryptedData));

I can not use a temp file to read/write between both programs.

ManyQuestions
  • 1,069
  • 1
  • 16
  • 34

4 Answers4

2
  1. Break up the encoded text and put the parts together like this:

    String encryptedData= "blahblahblah" + "moreblahblah" + "etcetera";

  2. Write the encrypted data to a text file and read it from there, using f.e. BufferedWriter/FileWriter and BufferedReader/FileReader.

Koen
  • 278
  • 1
  • 7
2

Don't use the toString form of the array to serialize the data.

The best solution is to write it to a file, then read it from a file. This can be done very easily using the Files utility class.

To write:

final byte[] encrypted = ...
final Path output = Paths.get(".", "encrypted.bin");
Files.write(output, encrypted);

And to read again:

final Path input = Paths.get(".", "encrypted.bin");
final byte[] encrypted = Files.readAllBytes(input);

To solve your immediate problem, you could Base64 encode your binary data. This would greatly reduce the size of the String representation. You can use the Base64 class available in the JDK.

To encode:

final byte[] encrypted = ...
final Base64.Encoder encoder = Base64.getEncoder();
System.out.println(encoder.encodeToString(encrypted));

To decode:

final String encoded = ...
final Base64.Decoder decoder = Base64.getDecoder();
final byte[] encrypted = decoder.decode(encoded);
Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
1

Maybe you should use an InputStream and not hardcode the string literal into your class?

jgroehl
  • 134
  • 6
0

I suggest using a file for temporary storage, but if you really need to convert your data to a string that must not be corrupted by character encodings, your best bet would be Base64.
You can use javax.xml.bind.DatatypeConverter to convert byte arrays to strings and vice versa (see parseBase64Binary and printBase64Binary).

Siguza
  • 21,155
  • 6
  • 52
  • 89