修复office文件密码判断

This commit is contained in:
陈精华 2022-12-28 13:35:34 +08:00
parent 2184264831
commit e0cc2b6a01
No known key found for this signature in database
GPG Key ID: 30BDC970902B755D
1 changed files with 12 additions and 7 deletions

View File

@ -1,12 +1,13 @@
package cn.keking.utils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.extractor.ExtractorFactory;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.springframework.lang.Nullable;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* Office工具类
@ -16,6 +17,8 @@ import java.io.FileInputStream;
*/
public class OfficeUtils {
private static final String POI_INVALID_PASSWORD_MSG = "Invalid password specified";
/**
* 判断officeword,excel,ppt文件是否受密码保护
*
@ -24,13 +27,15 @@ public class OfficeUtils {
*/
public static boolean isPwdProtected(String path) {
try {
ExtractorFactory.createExtractor(new FileInputStream(path));
} catch (EncryptedDocumentException e) {
return true;
ExtractorFactory.createExtractor(Files.newInputStream(Paths.get(path)));
} catch (IOException e) {
if (POI_INVALID_PASSWORD_MSG.equals(e.getMessage())) {
return true;
}
} catch (Exception e) {
Throwable[] throwableArray = ExceptionUtils.getThrowables(e);
for (Throwable throwable : throwableArray) {
if (throwable instanceof EncryptedDocumentException) {
if (throwable instanceof IOException && POI_INVALID_PASSWORD_MSG.equals(throwable.getMessage())) {
return true;
}
}
@ -48,7 +53,7 @@ public class OfficeUtils {
public static synchronized boolean isCompatible(String path, @Nullable String password) {
try {
Biff8EncryptionKey.setCurrentUserPassword(password);
ExtractorFactory.createExtractor(new FileInputStream(path));
ExtractorFactory.createExtractor(Files.newInputStream(Paths.get(path)));
} catch (Exception e) {
return false;
} finally {