I want to both compress and encrypt some data files and was playing around with Zip streams and Cipher streams. From what I can tell, the Cipher streams are wrapper classes, so you can't treat a Cipher stream as a Zip stream. Ideally, I would like to compress and then encrypt, but this isn't possible because, unless I am mistaken, there is no way to properly add a ZipEntry when the Zip stream is wrapped by a Cipher stream.
What's the best solution here? I could try encrypt and then compress, but I'm guessing that would give worse compression and performance, and might not even work. Or I could process the files using two seperate operations, first compress to temp files, then encrypt. Anyone have any thoughts on the best way to handle this?
Example code to compress and encrypt a list of files (this method was trimmed a bit to serve as a brief example):
public void compressAndEncrypt(List<File> inFiles, File outFile, SecretKey secretKey) throws Exception {
OutputStream outputStream = new FileOutputStream(outFile);
outputStream = new ZipOutputStream(outputStream);
Cipher cipher = Cipher.getInstance("AES");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
outputStream = new CipherOutputStream(outputStream, cipher);
for (File inFile : inFiles) {
FileInputStream inputStream = new FileInputStream(inFile);
ZipEntry zipEntry = new ZipEntry(inFile.getAbsolutePath());
// OOPS, this next line doesn't work, CipherOutputStream is not a subclass of ZipOutputStream
((ZipOutputStream) outputStream).putNextEntry(zipEntry);
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
}
outputStream.close();
}
Edited by: Skotty on Aug 18, 2009 5:54 AM
Edited by: Skotty on Aug 18, 2009 5:54 AM (removed leading tabs)
Edited by: Skotty on Aug 18, 2009 5:56 AM