Skip to content
Advertisement

Java AES Decryption with keyFile using BouncyCastle SSL

I am trying to write a Java code decrypt a file encrypted with AES256 using BouncyCastle compatible with OpenSSL decryption.

s_key is the file provided which contains the key that will be used to encrypt and decrypt

Steps to be done: 1 – Read the key file 2 – Use the key provided to decrypt file inputfilename

Below I have use so far but I am getting error:

JavaScript

Error:

JavaScript

Advertisement

Answer

When using a password, OpenSSL stores the ciphertext in a specific format, namely the ASCII encoding of Salted__, followed by the 8 bytes salt, then the actual ciphertext.

During decryption, the salt must not be randomly generated (as it is done in the posted code), otherwise the wrong key and IV will be derived. Instead, the salt must be determined from the metadata of the ciphertext. Also the use of the stream classes must be fixed:

JavaScript

This is functionally equivalent to the OpenSSL statement:

JavaScript

Note that OpenSSL applied MD5 as digest by default in earlier versions and SHA256 as of v.1.1.0. Code and OpenSSL statement must use the same digest for compatibility.
In the code the digest is explicitly specified, in the OpenSSL statement it can be explicitly set via the -md option so that matching is possible on both sides.
Keep in mind that EVP_BytesToKey(), which is used by default by OpenSSL for key derivation, is deemed insecure nowadays.


Addition regarding Java 8: For Java 8, e.g. the following implementation can be applied for the determination of the salt:

JavaScript

The loop is necessary because read(byte[],int,int), unlike readNBytes(int), does not guarantee that the buffer is completely filled (considering here the non-EOF and non-error case).

If you omit the loop (which means using the equivalent read(byte[])), the code will still run for those JVMs which also fill the buffer completely. Since this applies to the most common JVMs for small buffer sizes the code will mostly work, see the comment by dave_thompson_085. However, this is not guaranteed for any JVM and is therefore less robust (though probably not by much).

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement