修复office文件密码判断

pull/63/head
陈精华 2 years ago
parent 2184264831
commit e0cc2b6a01
No known key found for this signature in database
GPG Key ID: 30BDC970902B755D

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

Loading…
Cancel
Save