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);
}
To encrypt
HSSFyou simply doBiff8EncryptionKey.setCurrentUserPasswordbefore writing theHSSFWorkbook.Simplest example is as this:
This works for me. If I open
file.xlsusingExcelit asks me for password and if I typepassthere, the workbook opens.If the aim is encrypting an existing unencrypted workbook, then this would be as so:
So same solution. Simply do
Biff8EncryptionKey.setCurrentUserPasswordbefore writing theHSSFWorkbook.This code only creates correct encrypted workbooks for usage with
Microsoft Excel.LibreOffice Calcis not able to open those files. So seems encrypting method used is unknown forLibreOffice Calc. But I have not found a way to change encrypting method forHSSF. SoHSSFencryption seems not be fully provided inapache poi. Apache POI - Encryption support also not shows an example. So you are able opening and rewriting encryptedHSSFWorkbook. The new written workbook is encrypted too then ifBiff8EncryptionKey.setCurrentUserPasswordis not setnull. But you cannot write an encryptedHSSFWorkbookfrom scratch.