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.
source share