I am using Zip4j to convert some string data into a password protected zip file. Next I send this zip file as an attachment via email. Issue is that sometimes (failure rate like 4%, rest 96% of the time it works) I am unable to unzip (using unzip command on mac) the file that I receive in the email, the error received while unzipping the file is as below:
7 extra bytes at beginning or within zipfile
(attempting to process anyway)
file #1: bad zipfile offset (local header sig): 7
(attempting to re-compensate)
error: invalid compressed data to inflate
It seems the contents of the body that are in the zip file does not matter, for example: zipping and sending the email the first time does not work but doing this agin with same contents works. I am unable to reproduce this locally.
ByteArrayOutputStream byteArrayOutputStream = new
ByteArrayOutputStream();
net.lingala.zip4j.io.ZipOutputStream zipOutputStream = new
net.lingala.zip4j.io.ZipOutputStream(byteArrayOutputStream);
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
parameters.setEncryptFiles(true);
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
parameters.setPassword("zipFilePassword");
parameters.setFileNameInZip(subject + ".txt");
parameters.setSourceExternalStream(true);
zipOutputStream.putNextEntry(null, parameters);
zipOutputStream.write("some regular text".getBytes());
zipOutputStream.closeEntry();
zipOutputStream.finish();
DataSource attachment = new
ByteArrayDataSource(byteArrayOutputStream.toByteArray(),
"text/plain");
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(attachment));
messageBodyPart.setFileName(subject + ".zip");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
........
Some changes that I do plan to make is:
- Set mime type to application/zip instead of text/plain when creating an instance of ByteArrayDataSource.
- May be not use compression at all since the data that I am sending is very small, so use parameters.setCompressionMethod(Zip4jConstants.COMP_STORE);
Looked at this topic http://www.lingala.net/zip4j/forum/index.php?topic=434.msg1297#msg1297 , but that is applicable for AES encryption and here I am using the ENC_METHOD_STANDARD so I assume this does not apply.
Any idea what is going wrong?