使用 Apache POI 打开 .docx 并使用密码保存
Open .docx with Apache POI and save it with password
目标是打开现有的 .docx 文档并使用密码加密保存。
我为此使用 Apache POI 库。下面的代码工作正常,使文档加密和密码保护。
但是在创建文件后,我可以使用 LibreOffice 打开它,但不能使用 MS Word 或 OpenOffice Writer。
该文件似乎没有内容类型部分,因为 OpenOffice 向我询问了文件的过滤器。但是当我选择 "Microsoft Word 2007 XML" 时,我从 OpenOffice
得到了 "Common Input-Output error"
伙计们,我可以请你帮我吗?
P.S。
我使用 Java 8 和 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;
}
}
所以,我通过更改 EncryptionMode 解决了问题:
// EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard);
我发现一些信息表明免费(无付费)版本的 MS Word 不支持 ECMA-376.Agile 加密。所以,我将加密模式更改为 ECMA-376.Standard,它对我有用。
我不确定这是不是真的,但它对我的情况有帮助。
希望这会对某人有所帮助。
谢谢。
目标是打开现有的 .docx 文档并使用密码加密保存。 我为此使用 Apache POI 库。下面的代码工作正常,使文档加密和密码保护。
但是在创建文件后,我可以使用 LibreOffice 打开它,但不能使用 MS Word 或 OpenOffice Writer。
该文件似乎没有内容类型部分,因为 OpenOffice 向我询问了文件的过滤器。但是当我选择 "Microsoft Word 2007 XML" 时,我从 OpenOffice
得到了 "Common Input-Output error"伙计们,我可以请你帮我吗? P.S。 我使用 Java 8 和 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;
}
}
所以,我通过更改 EncryptionMode 解决了问题:
// EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard);
我发现一些信息表明免费(无付费)版本的 MS Word 不支持 ECMA-376.Agile 加密。所以,我将加密模式更改为 ECMA-376.Standard,它对我有用。 我不确定这是不是真的,但它对我的情况有帮助。
希望这会对某人有所帮助。
谢谢。