日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java实现文件加密(word、excel、pdf、ppt)

發布時間:2023/12/20 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java实现文件加密(word、excel、pdf、ppt) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

導航

  • 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)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。