I am trying to write Java code which can compress any file in .7z format and encrypt it with AES 256. I need to compress and encrypt a file through Java code and send it to a user. They then decompress the file on their Windows machine using 7zip software and give a password that was used to encrypt the file. I was able to achieve the first step which is compression as .7z, but I tried lot of different options for AES 256 encryption. The compressed file is encrypted, but I was not able to decompress and decrypt it in 7zip Windows software. I have given my Java code which I used to compress. How can I add the AES 256 encryption logic which can be later decompressed and decrypted in 7zip software?
import java.io.*;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.apache.commons.compress.archivers.sevenz.*;
public class LZMACompressionExample {
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
String inputFilePath = "D:\\f\\test.txt";
String outputFilePath = "D:\\c\\test.7z";
System.out.println("File compression completed.");
// create 7z archive with original file name
SevenZOutputFile sevenZOutput = new SevenZOutputFile(new File(outputFilePath));
SevenZArchiveEntry entry = sevenZOutput.createArchiveEntry(new File(inputFilePath), new File(inputFilePath).getName());
sevenZOutput.putArchiveEntry(entry);
// write compressed data to 7z archive
FileInputStream compressedFileInputStream = new FileInputStream(inputFilePath);
byte[] compressedBuffer = new byte[1024];
int compressedLen;
while ((compressedLen = compressedFileInputStream.read(compressedBuffer)) > 0) {
sevenZOutput.write(compressedBuffer, 0, compressedLen);
}
// close streams
sevenZOutput.closeArchiveEntry();
compressedFileInputStream.close();
sevenZOutput.close();
System.out.println("File compressed and saved in .7z format with original file name inside.");
}
}
I tried lot of AES 256 encryption Java logic. The file is encrypting, but I'm not able to open it in 7zip windows software. It throws an error.