I have pdf file in byte[] array. I want to compress it and encrypt with password. I don't want to create any temp files. But libraries like zip4j, winzipaes doesn't support it. They accept only File objects.
EDIT: code for simple zip:
public static byte[] zipBytes(String filename, byte[] input) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
ZipEntry entry = new ZipEntry(filename);
entry.setSize(input.length);
zos.putNextEntry(entry);
zos.write(input);
zos.closeEntry();
zos.close();
return baos.toByteArray();}
How add encryption and password?
A little late but hope this little snippet helps someone else. This is for zip4j on Java 7
private byte[] compressFileByZip(byte[] fileBytes, String filenameInZip, String zipFilePassword) throws ZipException {
// Zip into a ByteArrayOutputStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try(ZipOutputStream zos = new ZipOutputStream(baos)) {
ZipParameters zipParameters = new ZipParameters();
zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
zipParameters.setSourceExternalStream(true);
zipParameters.setFileNameInZip(filenameInZip);
// Set the encryption method to AES Zip Encryption
zipParameters.setEncryptFiles(true);
zipParameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
zipParameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
zipParameters.setPassword(zipFilePassword);
// Zip, flush and clean up
zos.putNextEntry(null, zipParameters);
zos.write(fileBytes);
zos.flush();
zos.closeEntry();
zos.close();
zos.finish();
} catch(IOException ioe) {
ioe.printStackTrace();
LOG.error("Error writing compressed file", ioe);
}
// Extract zipped file as byte array
byte[] byteCompressedFile = baos.toByteArray();
LOG.info("Zipped successfully");
return byteCompressedFile;
}
The section on encryption is optional.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With