import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
public class EncryptedJPEG {
private static final int ITERATION_COUNT = 65536;
private static final int KEY_LENGTH = 128;
public static void main(String[] args) throws Exception {
String password = "secret-password";
// Encode the JPEG
byte[] salt = new SecureRandom().generateSeed(8);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
SecretKey secretKey = factory.generateSecret(new PBEKeySpec(password.toCharArray(), salt, ITERATION_COUNT, KEY_LENGTH));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(new byte[16]);
PBEParameterSpec pbeParams = new PBEParameterSpec(salt, ITERATION_COUNT);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, pbeParams, iv);
FileInputStream fis = new FileInputStream("image.jpg");
FileOutputStream fos = new FileOutputStream("encrypted.jpg");
byte[] data = new byte[8192];
int len;
while ((len = fis.read(data)) > 0) {
fos.write(cipher.update(data, 0, len));
}
fos.write(cipher.doFinal());
fis.close();
fos.close();
// Decode the JPEG
fis = new FileInputStream("encrypted.jpg");
fos = new FileOutputStream("decrypted.jpg");
cipher.init(Cipher.DECRYPT_MODE, secretKey, pbeParams, iv);
while ((len = fis.read(data)) > 0) {
fos.write(cipher.update(data, 0, len));
}
fos.write(cipher.doFinal());
fis.close();
fos.close();
}
}