Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Effectively encrypting files using AES in java

I'm developing an application that should encrypt some small (less than 1MB) and large (about 500MB) files.
How can I encrypt files and save encrypted version somewhere on disk effectively (i.e.fast)?
Can I have encryption progress if it took time?

like image 659
Ariyan Avatar asked Aug 12 '12 06:08

Ariyan


People also ask

Which encryption algorithm is best in Java?

RC4 - Key size from 40-bit to 1024-bit, RC4 is the fastest java supported encryption algorithm.

What is AES encryption in Java?

AES, Advanced Encryption Standard is a block ciphertext encryption and decryption algorithm that processes a block of 128 bits of data using secret keys of 128, 192, or 256 bits. We will also discuss how this algorithm can be implemented using the Java programming language.

Does Java support AES 256?

AES 256 Encryption and Decryption Encrypting or decrypting a message or a string is supported by Java Cryptographic Extension (JCE) framework in Java.


1 Answers

Assuming you have an AES key and some output stream, here's how you could add an encryption decorator to the stream.

Cipher enc = Cipher.getInstance("AES/CBC/PKCS5Padding");
enc.init(Cipher.ENCRYPT_MODE, key);
AlgorithmParameters params = enc.getParameters();
IvParameterSpec iv = params.getParameterSpec(IvParameterSpec.class);
out.write(iv.getIV());
out = new CipherOutputStream(enc, out); 

This adds the IV to the beginning of the cipher text; when decrypting, you'd need to parse that out to initialize the cipher.

A better solution, longterm, would be to use library that implements the Cryptographic Message Syntax, the basis for S/MIME. This records metadata about the algorithms and keys that can be used for decryption.

I would also recommend an AEAD mode like GCM or CCM if your provider implements it. (The SunJCE does not.) These will verify that the file is decrypted correctly, and has not been corrupted.

like image 170
erickson Avatar answered Sep 22 '22 03:09

erickson