问题
The goal is to open existing .docx document and save it encrypted with password. I use Apache POI library for that. The code below works fine and makes document encrypted and password protected.
But after the file creating I can open it with the LibreOffice but can't with the MS Word or OpenOffice Writer.
It seems that the file has no content type part cuz OpenOffice asked me about file's filter. But when I choosed "Microsoft Word 2007 XML" I got the "Common Input-Output error" from the OpenOffice
Could I ask you to help me with it, guys? P.S. I use Java 8 and POI 3.17
static boolean encryptOne(String documentPath, String password) {
try {
POIFSFileSystem fs = new POIFSFileSystem();
EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
Encryptor encryptor = info.getEncryptor();
encryptor.confirmPassword(password);
OPCPackage opc = OPCPackage.open(new File(documentPath), PackageAccess.READ_WRITE);
opc.save(encryptor.getDataStream(fs));
opc.close();
FileOutputStream fos = new FileOutputStream(documentPath);
fs.writeFilesystem(fos);
fos.close();
System.out.println("Document successfully encrypted");
return true;
} catch (IOException | GeneralSecurityException | InvalidFormatException e) {
ExceptionPrinter.printOutStream(e);
return false;
}
}
回答1:
So, I solved the problem by changing EncryptionMode:
// EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard);
I found some information that free (no pay) versions of the MS Word don't support ECMA-376.Agile encryption. So, I changed encryption mode to ECMA-376.Standard and it works for me. I'm not sure that it's true but it helped in my case.
Hope this will help someone.
Thanks.
来源:https://stackoverflow.com/questions/51875706/open-docx-with-apache-poi-and-save-it-with-password