Effective file encryption using AES in java

I am developing an application that should encrypt some small (less than 1 MB) and large (about 500 MB) files.
How can I effectively encrypt files and save the encrypted version somewhere on disk (e.g. fast)?
Can I do encryption if it takes time?

+6
source share
2 answers

Assuming you have an AES key and some kind of output stream, here's how you can add an encryption decoder 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 IV to the beginning of the ciphertext; when decrypting, you will need to parse this to initialize the cipher.

The best solution, long-term, would be to use a library that implements the Cryptographic Message Syntax, the foundation for S / MIME. It records metadata about the algorithms and keys that can be used for decryption.

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

+6
source

As Bhavik mentioned, BouncyCastle would be a good way, its easy and mature. You can definitely see the progress of encryption, as you can control how much to read and write at once. You can read bytes from a file, encrypt them and write back to another file in the pipeline.

An example of this is mentioned in this question: How to encrypt a string / stream using bouncycastle pgp without starting with a file

+2
source

Source: https://habr.com/ru/post/922662/


All Articles