1

I know that similar questions have been asked, but I can't fix my problem with any of them.

I have an encrypted file which has been created with the following Unix command:

tar cf FILES | gzip | openssl enc -k PASSWORD -aes-256-cbc -e > OUTPUT.tar.gz.enc 

I can successfully decrypt the file with the associated command.

I have to decrypt this file in a Java process. I used the code presented in this SO answer.

I am using the same EVP_BytesToKey function but s slightly different main function.

This is how I load the encrypted file:

byte[] headerSaltAndCipherText = IOUtils.toByteArray(new
InputStreamReader(new FileInputStream(f)));

In the example code, it seems that the data is encoded in base64. However, when I read my file, it is not (I can see in clear the "Salted__" header)

I created the easCBC object this way:

Cipher aesCBC = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");

And I added Security.addProvider(new BouncyCastleProvider()); at the top of the main function. I started to use BouncyCastle as I was stuck but it didn't change a thing.

I also tried with PKCS7Padding and NoPadding but no luck.

The common issues that I found where about the wrong padding behing used or the encrypted data not being encoded/loaded properly.

As I am not doing exactly as in the example, I guess that the answer is the second solution: I tried loading the file as in the example but I have this exception java.nio.charset.MalformedInputException: Input length = 1 and anyway, I can't use features from the JDK 1.7.

What am I doing wrong?

Community
  • 1
  • 1
Flanfl
  • 516
  • 8
  • 29
  • 1
    For better help sooner, post your code as an [SSCCE](http://www.sscce.org) that demonstrates your problem. This allows users to copy/paste and reproduce your issue. – Duncan Jones Oct 10 '13 at 14:06

1 Answers1

0

If the input file is not character data (i.e. Base64 encoded) you should not be using an InputStreamReader, just read the bytes directly off the FileInputStream. If the input is Base64 encoded you need to read it in as character data and convert it to a byte[] using a Base64 decoder.

For padding, OpenSSL enc command uses PKCS5PADDING for block ciphers.

The other problem could be how your generating your key material and initialization vector. You have to do this the same way OpenSSL does given an input password.

Finally (though it seems you haven't run in to this yet) if you are using an Oracle Java Runtime Environment or JDK, you'll have to install the JCE Unlimited Strength policy files for your JRE in order to use AES256.

Dev
  • 11,919
  • 3
  • 40
  • 53
  • Removing `InputStreamReader` solved my problem thanks! I could not find which padding OpenSSL used. – Flanfl Oct 10 '13 at 15:14
  • @Flanfl To see what padding is being used, decrypt with `NoPadding` (or equivalent) and have a look at the end of the last block. That will show whatever padding has been added. – rossum Oct 10 '13 at 23:13