More than two years ago I posted this blog entry, where I showed a little utility for reading password-protected zip files in Java. Since then it seems it helped a lot of people and many asked if I could provide something for the other direction – i.e. writing encrypted files. Finally I’ve decided to add that as well as improve the original class for reading and recently I published a small open source project which provides both the ZipDecryptInputStream (for reading) as well as ZipEncryptOutputStream (for writing). The project is named ziputils and is available here: https://bitbucket.org/matulic/ziputils/overview.
The usage is very simple. ZipDecryptInputStream can be used in the same way as outlined in my old blog entry. ZipEncryptOutputStream which I added can be used in a very similar way:
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; // usage: java Main zip-file-name password filename1 [filename2 [filename3 [...]]] public class Main { public static void main(String[] args) throws IOException { // create a stream that will encrypt the resulting zip file // using the password provided in the second command line argument ZipEncryptOutputStream zeos = new ZipEncryptOutputStream(new FileOutputStream(args[0]), args[1]); // create the standard zip output stream, initialize it with our encrypting stream ZipOutputStream zos = new ZipOutputStream(zeos); // write the zip file for (int i = 2; i < args.length; i++) { ZipEntry ze = new ZipEntry(args[i]); zos.putNextEntry(ze); InputStream is = new FileInputStream(args[i]); int b; while ((b = is.read()) != -1) { zos.write(b); } zos.closeEntry(); } zos.close(); } }
You can find more about how to use the classes in the project javadoc. To download the ziputils jar, go to the project downloads page. Enjoy!