导航

  • FileEncryUtils
    • 测试环境
      • pom依赖
      • log4j.properties
    • 代码

FileEncryUtils

提供word、excel、pdf、ppt的加密

测试环境

JDK1.8+idea+maven

pom依赖

  <dependencies><dependency><groupId>com.itextpdf</groupId><artifactId>itext7-core</artifactId><version>7.1.4</version><type>pom</type></dependency><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.28</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.17</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.17</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>ooxml-schemas</artifactId><version>1.1</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.17</version></dependency><dependency><groupId>fr.opensagres.xdocreport</groupId><artifactId>fr.opensagres.xdocreport.converter.docx.xwpf</artifactId><version>1.0.6</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.10</version><scope>test</scope></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.21</version></dependency><!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 --><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.25</version><scope>compile</scope></dependency><!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api<dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.25</version></dependency>--></dependencies>

log4j.properties

#定义输出级别
log4j.rootLogger=DEBUG,Console
#日志输出方式:控制台输出log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.Encoding=UTF-8#可以灵活地指定布局模式
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
#log4j.appender.Console.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss.SSS} -%p (%F\:%L)- %m%n
#打印格式例子:2017-08-11 15:36 -DEBUG (HttpServletBean.java:174)- Servlet 'mvc' configured successfully
log4j.appender.Console.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm} -%p (%F\:%L)- %m%n

代码

package util;import java.io.*;import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.EncryptionMode;
import org.apache.poi.poifs.crypt.Encryptor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;import com.itextpdf.kernel.pdf.EncryptionConstants;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.ReaderProperties;
import com.itextpdf.kernel.pdf.WriterProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;/*** @author :Lizhipeng* @date :Created in 2020/5/27 14:29* @description:* @modified By:* @version:*/
public class FileEncryUtils {private static Logger LOGGER = LoggerFactory.getLogger(FileEncryUtils.class);/*** 加密WORD文档(doc)* @param sourceFilePath  源文件* @param targetFilePath  目标文件* @param password           密码* @return* @throws Exception*/public static boolean encrypDOC(String sourceFilePath, String targetFilePath, String password) throws Exception{return encrypDOC(sourceFilePath, new FileOutputStream(targetFilePath), password);}public static boolean encrypDOC(String sourceFilePath, OutputStream out, String password) throws IOException {POIFSFileSystem fs = null;HWPFDocument doc = null;try {fs = new POIFSFileSystem(new FileInputStream(sourceFilePath));doc = new HWPFDocument(fs);Biff8EncryptionKey.setCurrentUserPassword(password);doc.write(out);return true;} catch (Exception e) {LOGGER.error("DOC文档加密失败:{}",e.getMessage());return false;}finally {
//            FileUtils.close(doc);doc.close();
//            FileUtils.close(fs);fs.close();
//            FileUtils.close(out);out.close();}}/*** 加密EXCEL文档(xls)* @param sourceFilePath    源文件* @param targetFilePath  目标文件* @param password           密码* @return* @throws Exception*/public static boolean encrypXLS(String sourceFilePath, String targetFilePath, String password) throws Exception{return encrypXLS(sourceFilePath, new FileOutputStream(targetFilePath), password);}public static boolean encrypXLS(String sourceFilePath, OutputStream out, String password) throws IOException {POIFSFileSystem fs = null;HSSFWorkbook hwb = null;try {fs = new POIFSFileSystem(new FileInputStream(sourceFilePath));hwb = new HSSFWorkbook(fs);Biff8EncryptionKey.setCurrentUserPassword(password);hwb.write(out);return true;} catch (Exception e) {LOGGER.error("XLS文档加密失败:{}",e.getMessage());return false;}finally {
//            FileUtils.close(hwb);
//            FileUtils.close(fs);
//            FileUtils.close(out);hwb.close();fs.close();out.close();}}/*** 加密PPT文档(ppt)* @param sourceFilePath   源文件* @param targetFilePath  目标文件* @param password           密码* @return* @throws Exception*/public static boolean encrypPPT(String sourceFilePath, String targetFilePath, String password) throws Exception{return encrypPPT(sourceFilePath, new FileOutputStream(targetFilePath), password);}public static boolean encrypPPT(String sourceFilePath, OutputStream out, String password) throws IOException {POIFSFileSystem fs = null;HSLFSlideShow hss = null;try {fs = new POIFSFileSystem(new FileInputStream(sourceFilePath));hss = new HSLFSlideShow(fs);Biff8EncryptionKey.setCurrentUserPassword(password);hss.write(out);return true;} catch (Exception e) {LOGGER.error("PPT文档加密失败:{}",e.getMessage());return false;}finally {
//            FileUtils.close(hss);
//            FileUtils.close(fs);
//            FileUtils.close(out);hss.close();fs.close();out.close();}}/*** 加密PDF文档* @param sourceFilePath    源文件* @param targetFilePath  目标文件* @param password           密码* @return* @throws Exception*/public static boolean encrypPDF(String sourceFilePath, String targetFilePath, String password) throws Exception{return encrypPDF(sourceFilePath, new FileOutputStream(targetFilePath), password);}public static boolean encrypPDF(String sourceFilePath, OutputStream out, String password) throws IOException {PdfDocument pdfDoc = null;PdfReader reader = null;try {reader = new PdfReader(sourceFilePath, new ReaderProperties().setPassword("World".getBytes()));PdfWriter writer = new PdfWriter(out,new WriterProperties().setStandardEncryption(password.getBytes(), password.getBytes(),EncryptionConstants.EMBEDDED_FILES_ONLY,EncryptionConstants.ENCRYPTION_AES_128 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA));pdfDoc = new PdfDocument(reader, writer);return true;} catch (Exception e) {LOGGER.error("PDF文档加密失败:{}",e.getMessage());return false;}finally {
//            FileUtils.close(pdfDoc);
//            FileUtils.close(reader);pdfDoc.close();reader.close();}}/*** 加密xml文档(docx,xlsx,pptx)* @param sourceFilePath  源文件* @param targetFilePath  目标文件* @param password           密码* @return* @throws Exception*/public static boolean encrypXML(String sourceFilePath, String targetFilePath, String password)  throws Exception{return encrypXML(sourceFilePath, new FileOutputStream(targetFilePath), password);}public static boolean encrypXML(String sourceFilePath, OutputStream out, String password) throws IOException {POIFSFileSystem fs = null;try {fs = new POIFSFileSystem();EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);Encryptor enc = info.getEncryptor();enc.confirmPassword(password);try (OPCPackage opc = OPCPackage.open(new File(sourceFilePath), PackageAccess.READ_WRITE);OutputStream os = enc.getDataStream(fs)) {opc.save(os);}fs.writeFilesystem(out);return true;} catch (Exception e) {LOGGER.error("XML文档加密失败:{}",e.getMessage());return false;} finally {
//            FileUtils.close(fs);
//            FileUtils.close(out);fs.close();out.close();}}/*** 加密文档* @param sourceFilePath   源文件* @param targetFilePath  目标文件* @param password           密码* @return*/public static boolean encryFile(String sourceFilePath, String targetFilePath, String password){try {return encryFile(sourceFilePath, new FileOutputStream(targetFilePath), password);} catch (Exception e) {LOGGER.error("文档加密失败:{}",e.getMessage());}return false;}public static boolean encryFile(String sourceFilePath, OutputStream out, String password){boolean flag = false;try {int index = sourceFilePath.indexOf(".");if(index > 0) {String suffix = sourceFilePath.substring(index+1);if("doc".equalsIgnoreCase(suffix)) {flag = encrypDOC(sourceFilePath, out, password);}else if("xls".equalsIgnoreCase(suffix)) {flag = encrypXLS(sourceFilePath, out, password);}else if("ppt".equalsIgnoreCase(suffix)) {flag = encrypPPT(sourceFilePath, out, password);}else if("pdf".equalsIgnoreCase(suffix)) {flag = encrypPDF(sourceFilePath, out, password);}else if("docx".equalsIgnoreCase(suffix) || "xlsx".equalsIgnoreCase(suffix) || "pptx".equalsIgnoreCase(suffix)){flag = encrypXML(sourceFilePath, out, password);}else {LOGGER.warn("无法识别的文件类型");}}} catch (Exception e) {LOGGER.error("文档加密失败:{}",e.getMessage());}return flag;}/*** 简单测试* @param args*//*public static void main(String[] args) {boolean flag = FileEncryUtils.encryFile("C:/Users/Lzp's_computer/Desktop/测试文件.docx", "加密.docx", "password");LOGGER.info(String.valueOf(flag));}*/
}

遇到的错误:

SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

解决办法:导入slf4j12这个依赖(slf4j-nop也行),只用slf4j-api会报错

有更简单粗暴的文件加密方法或思路请不吝赐教

参考代码

代码原作者

java实现文件加密(word、excel、pdf、ppt)相关推荐

  1. Java通过openOffice实现word,excel,ppt转成pdf实现在线预览

    Java通过openOffice实现word,excel,ppt转成pdf实现在线预览 一.OpenOffice 1.1 下载地址 1.2 JodConverter 1.3 新建实体类PDFDemo ...

  2. office 文档 在线预览功能实现(word,excel,pdf,ppt等多种格式)——使用https://view.xdocin.com/view 提示文档过期——基础积累

    web实现office文档在线预览功能--基础积累 最近遇到一个需求,就是要实现多种文档链接的在线预览,最简单的方式就是通过window.open(url地址)的方式来实现. 但是如果要求是在一个弹窗 ...

  3. java poi- 实现 word Excel pdf ppt 转 HTML

    所需要 jar poi-3.17.jar poi-examples-3.17.jar poi-excelant-3.17.jar poi-ooxml-3.17.jar poi-ooxml-schema ...

  4. 微信公众号如何设置关键词回复Word/Excel/pdf/ppt等文件?

    大家好,我是运营小薇老师,今天给大家带来的课程是:<公众号如何设置关键词回复指定文件>,各位同学要认真听讲哦! 各位同学,大家都知道微信公众号有一个自动回复的功能,看看公众号后台,它可以设 ...

  5. txt doc rtf html,JAVA读取WORD,EXCEL,PDF,TXT,RTF,HTML文件文本内容的方法示例.docx

    JAVA读取WORD,EXCEL,PDF,TXT,RTF,HTML文件文本内容的方法示例 JAVA读取WORD,EXCEL,PDF,TXT,RTF,HTML文件文本内容的方法示例??2012-06-2 ...

  6. java全文检索word中的内容_搜索引擎时对WORD,EXCEL,PDF,POWERPOINT文件全文检索的总结...

    搜索引擎时对WORD,EXCEL,PDF,POWERPOINT文件全文检索的总结 (2012-02-12 16:31:59) 标签: pdf文档 幻灯片 pdf文件 全文检索 控件 it JAVA读取 ...

  7. java操作word/excel/pdf等文件技术方案

    最近项目中遇到很多对word/excel/pdf等文件的操作,解决方案有好多,开源免费有:利用openoffice组件(需要安装openoffice软件),poi,itext等.也有收费的服务:asp ...

  8. Web方式预览Office/Word/Excel/pdf文件解决方案

    Web方式预览Office/Word/Excel/pdf文件解决方案 参考文章: (1)Web方式预览Office/Word/Excel/pdf文件解决方案 (2)https://www.cnblog ...

  9. 在线查看word,excel,pdf文件解决

    眼看着项目要结束,提出新的需求(-_-!!习惯成自然了)需要支持在线查看word,excel,pdf文件,网页中嵌套word的时候,不让word文档占据整个网页,页面内还要有审批等功能,第一感觉想到控 ...

最新文章

  1. 原生与html,解析原生与html之间进行的一些关联
  2. C#编程(三十三)----------Array类
  3. spring整合xfire
  4. projective2d matlab
  5. 计算机安全模式启动时蓝屏,电脑如何进入安全模式修复蓝屏故障
  6. SocketTool
  7. win10如何固定ip地址
  8. 看拉扎维《模拟CMOS集成电路设计》的一些总结和思考(一)——绪论
  9. stm32F407 调试 LAN8720A ping不通问题解决
  10. 崂山道士“法术”已成真?还需VR+AI+5G三强紧联合
  11. 黑马day15作业2,3
  12. 林锐-《我的大学十年》
  13. 电子科技大学信通2018级学生上早自习缺勤率情况分析
  14. 地球系统模式(CESM)
  15. STC15系列单片机与 OV7670 SCCB通讯
  16. 如何判断一个整型数字是不是对称数字
  17. yolov5增加一层小目标检测层
  18. 子网掩码,CIDR前缀法表示掩码
  19. Java实现 历史上的今天
  20. ipad协议720版本

热门文章

  1. 现代法谱估计(2)Levinson-Durbin递推算法MATLAB及Python实现
  2. ajax数据交互 手动搭建后台
  3. 07 Android 植物人大战僵尸-修复放置卡片重叠Bug
  4. firmware upgrade encountered an issue.please select recovery mode in kies try again
  5. 网上银行安全手段面面观
  6. 如何自己搭建短链接服务
  7. OKR与CFR管理模式(一)-什么是OKR?
  8. 维护万星开源向量数据库是什么体验
  9. 互联网女皇发布年度互联网报告:强调Google机器学习准确性
  10. 封锁ppstream,pplive,qqlive