Open .docx with Apache POI and save it with password

我的未来我决定 提交于 2020-01-30 11:34:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!