Using AES to effectively encrypt files in Java

I am developing an application that should encrypt some small (less than 1MB) and large (about 500MB) files

Solution

Suppose you have an AES key and some output streams, here is how to 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 IV to the beginning of the ciphertext; When decrypting, you need to parse it to initialize the password

A better long-term solution is to use a library that implements encrypted message syntax, which is the basis of S / mime This records metadata about the algorithms and keys available for decryption

If your provider implements it, I will also recommend aead mode such as GCM or CCM (sunjce does not.) These will verify that the file is decrypted correctly and is not corrupted

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>