I'm trying to apply encryption to a binary xls file with Apache POI. While I can successfully encrypt xml based files, if I encrypt a binary one I can't open it and I get the wrong password error.
This is my code:
@Test
public void testEncryption() throws Exception {
File file = new File("file.xls");
Workbook workbook = new HSSFWorkbook();
setData(workbook);
FileOutputStream fileOutputStream = new FileOutputStream(file);
workbook.write(fileOutputStream);
fileOutputStream.close();
encryptFile(file, "pass");
}
public void encryptFile(File file, String encryptKey) throws Exception {
FileInputStream fileInput = new FileInputStream(file.getPath());
BufferedInputStream bufferInput = new BufferedInputStream(fileInput);
POIFSFileSystem poiFileSystem = new POIFSFileSystem(bufferInput);
Biff8EncryptionKey.setCurrentUserPassword(encryptKey);
HSSFWorkbook workbook = new HSSFWorkbook(poiFileSystem, true);
FileOutputStream fileOut = new FileOutputStream(file.getPath());
workbook.writeProtectWorkbook(Biff8EncryptionKey.getCurrentUserPassword(), "");
workbook.write(fileOut);
bufferInput.close();
fileOut.close();
Biff8EncryptionKey.setCurrentUserPassword(null);
}