word、pdf、excel及zip加密(含示例效果及工具类)

[复制链接]
发表于 2026-1-30 06:17:01 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
需求阐明:

许多人渴望可以或许对自己的Office文件以及压缩的ZIP文件举行加密,以防止未经授权的访问和信息泄漏。然而,使用WPS、Microsoft Office软件或别的压缩工具逐一对每一个文件举行加密,着实是耗时且费力,通常让人感到疲劳与沮丧。
因此,本文将详细先容一种更为高效的办理方案,以免各人在人力和时间上面无谓的斲丧。本文的重要内容布局包罗以下几个部分:
1、所需依赖
2、文档类加密工具类 + 测试示例
3、zip包加密工具类 + 测试示例
效果如下:


1、所需依赖:

提前声明(JAR包版本已经颠末筛选 只管不消对依赖做变动,否则部分方法大概类不存在)且注意各个POI依赖之间的版本信息。
  1.   <!--其他包 与主题无关 为保完整性故完整列出 -->
  2.     <dependency>
  3.         <groupId>org.springframework.boot</groupId>
  4.         <artifactId>spring-boot-starter</artifactId>
  5.     </dependency>
  6.     <dependency>
  7.         <groupId>org.springframework.boot</groupId>
  8.         <artifactId>spring-boot-starter-test</artifactId>
  9.         <scope>test</scope>
  10.     </dependency>
  11.     <dependency>
  12.         <groupId>junit</groupId>
  13.         <artifactId>junit</artifactId>
  14.         <version>4.13.1</version>
  15.         <scope>test</scope>
  16.     </dependency>
  17.     <dependency>
  18.         <groupId>org.slf4j</groupId>
  19.         <artifactId>slf4j-api</artifactId>
  20.         <version>1.7.21</version>
  21.     </dependency>
  22.     <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
  23.     <dependency>
  24.         <groupId>org.slf4j</groupId>
  25.         <artifactId>slf4j-log4j12</artifactId>
  26.         <version>1.7.25</version>
  27.         <scope>compile</scope>
  28.     </dependency>
  29.     <!-- office加密所需 -->
  30.     <dependency>
  31.         <groupId>org.apache.pdfbox</groupId>
  32.         <artifactId>pdfbox</artifactId>
  33.         <version>2.0.27</version>
  34.     </dependency>
  35.     <dependency>
  36.         <groupId>com.itextpdf</groupId>
  37.         <artifactId>itext7-core</artifactId>
  38.         <version>7.1.11</version>
  39.         <type>pom</type>
  40.     </dependency>
  41.     <dependency>
  42.         <groupId>org.freemarker</groupId>
  43.         <artifactId>freemarker</artifactId>
  44.     </dependency>
  45.     <!-- Apache POI -->
  46.     <dependency>
  47.         <groupId>org.apache.poi</groupId>
  48.         <artifactId>poi</artifactId>
  49.         <version>5.2.3</version>
  50.     </dependency>
  51.     <dependency>
  52.         <groupId>org.apache.poi</groupId>
  53.         <artifactId>poi-ooxml</artifactId>
  54.         <version>5.2.3</version>
  55.     </dependency>
  56.     <dependency>
  57.         <groupId>org.apache.poi</groupId>
  58.         <artifactId>poi-ooxml-schemas</artifactId>
  59.         <version>4.1.2</version>
  60.     </dependency>
  61.     <dependency>
  62.         <groupId>org.apache.xmlbeans</groupId>
  63.         <artifactId>xmlbeans</artifactId>
  64.         <version>5.1.1</version>
  65.     </dependency>
  66.     <dependency>
  67.         <groupId>org.apache.commons</groupId>
  68.         <artifactId>commons-collections4</artifactId>
  69.         <version>4.4</version>
  70.     </dependency>
  71.     <dependency>
  72.         <groupId>fr.opensagres.xdocreport</groupId>
  73.         <artifactId>fr.opensagres.xdocreport.converter.docx.xwpf</artifactId>
  74.         <version>1.0.6</version>
  75.     </dependency>
  76.     <!--ZIP包加密 所需  -->
  77.     <dependency>
  78.         <groupId>net.lingala.zip4j</groupId>
  79.         <artifactId>zip4j</artifactId>
  80.         <version>2.9.1</version>
  81.     </dependency>
复制代码
2、文档加密方法工具类:

  1.   package com.example.demo;
  2. import org.apache.pdfbox.pdmodel.PDDocument;
  3. import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
  4. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  5. import org.apache.poi.poifs.crypt.EncryptionInfo;
  6. import org.apache.poi.poifs.crypt.EncryptionMode;
  7. import org.apache.poi.poifs.crypt.Encryptor;
  8. import org.apache.poi.poifs.crypt.standard.StandardEncryptor;
  9. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  10. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  11. import org.apache.poi.xwpf.usermodel.XWPFDocument;
  12. import java.io.*;
  13. import java.nio.file.Files;
  14. /**
  15. * 类描述:文件加密工具类 (word、excel、pdf )
  16. * 如有新增 请补充到描述中。
  17. *
  18. * @author xú
  19. * @since 1.0.0  2024-08-27 04:45:19
  20. */
  21. public class DocumentEncryptionUtil {
  22.     private DocumentEncryptionUtil() {
  23.     }
  24.     /**
  25.      * 方法描述:加密word文件
  26.      *
  27.      * @param file     文件
  28.      * @param password 密码
  29.      * @author xú
  30.      * @since 1.0.0   2024-08-27 04:46:54
  31.      */
  32.     public static void encryptWordFile(File file, String password) {
  33.         try (POIFSFileSystem fs = new POIFSFileSystem();
  34.              FileInputStream fis = new FileInputStream(file);
  35.              XWPFDocument document = new XWPFDocument(fis)) {
  36.             EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
  37.             Encryptor encryptor = info.getEncryptor();
  38.             encryptor.confirmPassword(password);
  39.             try (OutputStream os = encryptor.getDataStream(fs)) {
  40.                 document.write(os);
  41.             }
  42.             try (FileOutputStream fos = new FileOutputStream(file)) {
  43.                 fs.writeFilesystem(fos);
  44.             }
  45.             //System.out.println("Encrypted Word file: " + file.getAbsolutePath());
  46.         } catch (org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException e) {
  47.             //System.out.println("已加密");
  48.         } catch (Exception e) {
  49.             e.printStackTrace();
  50.         }
  51.     }
  52.     /**
  53.      * 方法描述:加密excel-xlsx
  54.      *
  55.      * @param file     文件
  56.      * @param password 密码
  57.      * @author xú
  58.      * @since 1.0.0   2024-08-27 05:10:51
  59.      */
  60.     public static void encryptExcelXlsx(File file, String password) {
  61.         try (POIFSFileSystem fs = new POIFSFileSystem();
  62.              FileInputStream fis = new FileInputStream(file);
  63.              XSSFWorkbook workbook = new XSSFWorkbook(fis)) {
  64.             EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
  65.             Encryptor encryptor = info.getEncryptor();
  66.             encryptor.confirmPassword(password);
  67.             try (OutputStream os = encryptor.getDataStream(fs)) {
  68.                 workbook.write(os);
  69.             }
  70.             try (FileOutputStream fos = new FileOutputStream(file)) {
  71.                 fs.writeFilesystem(fos);
  72.             }
  73.             //System.out.println("Encrypted Excel file: " + file.getAbsolutePath());
  74.         } catch (org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException e) {
  75.             //System.out.println("已加密");
  76.         } catch (Exception e) {
  77.             e.printStackTrace();
  78.         }
  79.     }
  80.     /**
  81.      * 方法描述:加密excel-xls
  82.      *
  83.      * @param file     文件
  84.      * @param password 密码
  85.      * @author xú
  86.      * @since 1.0.0   2024-08-27 05:10:45
  87.      */
  88.     public static void encryptExcelXls(File file, String password) {
  89.         try (POIFSFileSystem fs = new POIFSFileSystem(); FileInputStream fis = new FileInputStream(file);
  90.              HSSFWorkbook workbook = new HSSFWorkbook(fis)) {
  91.             EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard);
  92.             StandardEncryptor encryptor = (StandardEncryptor) info.getEncryptor();
  93.             encryptor.confirmPassword(password);
  94.             try (OutputStream os = encryptor.getDataStream(fs)) {
  95.                 workbook.write(os);
  96.             }
  97.             try (FileOutputStream fos = new FileOutputStream(file)) {
  98.                 fs.writeFilesystem(fos);
  99.             }
  100.             System.out.println("Encrypted Excel file: " + file.getAbsolutePath());
  101.         } catch (Exception e) {
  102.             e.printStackTrace();
  103.         }
  104.     }
  105.     /**
  106.      * 方法描述:加密pdf文件
  107.      *
  108.      * @param file     文件
  109.      * @param password 密码
  110.      * @author xú
  111.      * @since 1.0.0   2024-08-27 04:46:05
  112.      */
  113.     public static void encryptPdfFile(File file, String password) {
  114.         try (PDDocument document = PDDocument.load(file)) {
  115.             // Set the encryption options
  116.             StandardProtectionPolicy policy = new StandardProtectionPolicy(password, password, new org.apache.pdfbox.pdmodel.encryption.AccessPermission());
  117.             policy.setEncryptionKeyLength(128); // You can set the key length to 128 or 256 bits
  118.             document.protect(policy);
  119.             document.save(file);
  120.             //System.out.println("Encrypted PDF file: " + file.getAbsolutePath());
  121.         } catch (org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException e) {
  122.             //System.out.println("已加密");
  123.         } catch (Exception e) {
  124.             e.printStackTrace();
  125.         }
  126.     }
  127. }
复制代码
测试文档加密工具类

3、测试及测试效果展示:
  1. public static void main(String[] args) {
  2.         String directoryPath = "D:\\桌面\\项目文档"; // 替换为你本地的路径
  3.         String backupDirectoryPath = "D:\\桌面\\备份"; // 替换为你的备份路径
  4.         String password = "aaaaa111112DDD";  // 密码设置
  5.         try {
  6.             Files.createDirectories(Paths.get(backupDirectoryPath));
  7.             Files.walkFileTree(Paths.get(directoryPath), new SimpleFileVisitor<>() {
  8.                 @Override
  9.                 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
  10.                     String fileName = file.getFileName().toString().toLowerCase();
  11.                     if (fileName.endsWith(".docx") || fileName.endsWith(".xlsx") || fileName.endsWith(".pdf")) {
  12.                         Path backupFile = Paths.get(backupDirectoryPath, file.toString().substring(directoryPath.length()));
  13.                         Files.createDirectories(backupFile.getParent());
  14.                         Files.copy(file, backupFile, StandardCopyOption.REPLACE_EXISTING);
  15.                         try {
  16.                             if (fileName.endsWith(".docx")) {
  17.                                 encryptWordFile(file.toFile(), password);
  18.                             } else if (fileName.endsWith(".xlsx")) {
  19.                                 encryptExcelFile(file.toFile(), password);
  20.                             } else if (fileName.endsWith(".pdf")) {
  21.                                 encryptPdfFile(file.toFile(), password);
  22.                             }
  23.                         }catch (Exception ex){
  24.                             ex.printStackTrace();
  25.                         }
  26.                         System.out.println("Processed file: " + file.toString());
  27.                     } else {
  28.                         System.out.println("Skipped file: " + file.toString());
  29.                     }
  30.                     return FileVisitResult.CONTINUE;
  31.                 }
  32.                 @Override
  33.                 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
  34.                     Path backupDir = Paths.get(backupDirectoryPath, dir.toString().substring(directoryPath.length()));
  35.                     Files.createDirectories(backupDir);
  36.                     System.out.println("Directory: " + dir.toString());
  37.                     return FileVisitResult.CONTINUE;
  38.                 }
  39.             });
  40.         } catch (IOException e) {
  41.             e.printStackTrace();
  42.         }
  43.     }
复制代码
4、 zip包加密工具类

  1. package com.example.demo;
  2. import net.lingala.zip4j.ZipFile;
  3. import net.lingala.zip4j.model.FileHeader;
  4. import net.lingala.zip4j.model.ZipParameters;
  5. import net.lingala.zip4j.model.enums.CompressionLevel;
  6. import net.lingala.zip4j.model.enums.CompressionMethod;
  7. import net.lingala.zip4j.model.enums.EncryptionMethod;
  8. import java.io.File;
  9. import java.io.IOException;
  10. import java.nio.file.Files;
  11. import java.util.ArrayList;
  12. import java.util.List;
  13. import java.util.Objects;
  14. /**
  15. * 类描述:zip包加密工具类
  16. *
  17. * @author xú chūn chéng
  18. * @version 1.0.0
  19. * @since 1.0.0  2024-08-27 04:49:55
  20. */
  21. public class ZipEncryptionUtil {
  22.     private ZipEncryptionUtil() {
  23.     }
  24.     /**
  25.      * 方法描述:使用旧zip创建加密zip
  26.      *
  27.      * @param oldZipFile 需要加密的zip包文件
  28.      * @param password   密码
  29.      * @author xú
  30.      * @since 1.0.0   2024-08-27 04:49:50
  31.      */
  32.     public static void createEncryptedZipWithOldZip(File oldZipFile, String password) {
  33.         //创建新的加密zip文件
  34.         String newZipFileName = oldZipFile.getParent() + File.separator + "encrypted_" + oldZipFile.getName();
  35.         try (ZipFile newEncryptedZipFile = new ZipFile(newZipFileName, password.toCharArray())) {
  36.             //设置加密的zip参数
  37.             ZipParameters zipParameters = new ZipParameters();
  38.             zipParameters.setCompressionMethod(CompressionMethod.DEFLATE);
  39.             zipParameters.setCompressionLevel(CompressionLevel.NORMAL);
  40.             zipParameters.setEncryptFiles(true);
  41.             zipParameters.setEncryptionMethod(EncryptionMethod.AES);
  42.             // 将旧的zip文件添加到新的加密zip文件中
  43.             newEncryptedZipFile.addFile(oldZipFile, zipParameters);
  44.         } catch (IOException e) {
  45.             throw new RuntimeException(e);
  46.         }
  47.         //System.out.println("Created encrypted ZIP file: " + newZipFileName);
  48.     }
  49.     /**
  50.      * 方法描述:加密zip文件 (会把OLD压缩文件解压开  然后重新打包加密) 慎用
  51.      * ( 这种加密方式存在问题  当文件内部多层级的时候无法正常加密 且中文乱码)
  52.      *
  53.      * @param file     文件
  54.      * @param password 密码
  55.      * @author xú chūn chéng
  56.      * @since 1.0.0   2024-08-27 04:48:46
  57.      */
  58.     public static void encryptZipFile(File file, String password) {
  59.         try {
  60.             File tempDir;
  61.             try (ZipFile zipFile = new ZipFile(file, password.toCharArray())) {
  62.                 // 设置压缩文件
  63.                 ZipParameters zipParameters = new ZipParameters();
  64.                 zipParameters.setCompressionMethod(CompressionMethod.DEFLATE);
  65.                 zipParameters.setCompressionLevel(CompressionLevel.NORMAL);
  66.                 zipParameters.setEncryptFiles(true);
  67.                 zipParameters.setEncryptionMethod(EncryptionMethod.AES);
  68.                 //将所有文件解压缩到临时目录
  69.                 tempDir = Files.createTempDirectory("zip4j").toFile();
  70.                 zipFile.extractAll(tempDir.getAbsolutePath());
  71.                 // 从zip中删除所有文件
  72.                 List<FileHeader> fileHeaders = zipFile.getFileHeaders();
  73.                 List<FileHeader> headersToRemove = new ArrayList<>(fileHeaders); // 将要删除的文件头收集到一个新列表中
  74.                 for (FileHeader fileHeader : headersToRemove) {
  75.                     zipFile.removeFile(fileHeader);
  76.                 }
  77.                 //使用加密重新打包文件
  78.                 for (File extractedFile : Objects.requireNonNull(tempDir.listFiles())) {
  79.                     zipFile.addFile(extractedFile, zipParameters);
  80.                 }
  81.             }
  82.             //清理临时目录
  83.             for (File extractedFile : Objects.requireNonNull(tempDir.listFiles())) {
  84.                 extractedFile.delete();
  85.             }
  86.             tempDir.delete();
  87.             //System.out.println("Encrypted ZIP file: " + file.getAbsolutePath());
  88.         } catch (IOException e) {
  89.             e.printStackTrace();
  90.         }
  91.     }
  92. }
复制代码
5、ZIP 方式1测试:

  1. public static void main(String[] args) {
  2.         String directoryPath = "D:\\桌面\\新建文件夹\\已压缩_未归类"; // 替换为你本地的路径
  3.         String backupDirectoryPath = "D:\\桌面\\备份"; // 替换为你的备份路径
  4.         String password = "741841aaa333.";//密码
  5.         long maxSize = 1024L * 1024L * 1024L; // 1GB
  6.         try {
  7.             Files.createDirectories(Paths.get(backupDirectoryPath));
  8.             // 首先收集所有要处理的文件
  9.             List<Path> filesToProcess = new ArrayList<>();
  10.             Files.walkFileTree(Paths.get(directoryPath), new SimpleFileVisitor<>() {
  11.                 @Override
  12.                 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
  13.                     String fileName = file.getFileName().toString().toLowerCase();
  14.                      //由于超过1G的文件处理时间过长 所需对此文件大小进行限制 最大为1GB
  15.                     if (fileName.endsWith(".zip") && Files.size(file) <= maxSize) {
  16.                         filesToProcess.add(file);
  17.                     }
  18.                     return FileVisitResult.CONTINUE;
  19.                 }
  20.                 @Override
  21.                 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
  22.                     Path backupDir = Paths.get(backupDirectoryPath, dir.toString().substring(directoryPath.length()));
  23.                     Files.createDirectories(backupDir);
  24.                     return FileVisitResult.CONTINUE;
  25.                 }
  26.             });
  27.             // 然后处理收集到的文件
  28.             int totalFiles = filesToProcess.size();
  29.             for (int i = 0; i < totalFiles; i++) {
  30.                 Path file = filesToProcess.get(i);
  31.                 Path backupFile = Paths.get(backupDirectoryPath, file.toString().substring(directoryPath.length()));
  32.                 Files.createDirectories(backupFile.getParent());
  33.                 Files.copy(file, backupFile, StandardCopyOption.REPLACE_EXISTING);
  34.                 ZipEncryptionUtil.encryptZipFile(file.toFile(), password);
  35.                 // 记录进度
  36.                 System.out.printf("Processed file (%d/%d): %s%n", i + 1, totalFiles, file.toString());
  37.             }
  38.         } catch (IOException e) {
  39.             e.printStackTrace();
  40.         }
  41.     }
复制代码
6:zip2加密方式测试 :

须要创建一个新的 ZIP 文件,并将原有的 ZIP 文件(OLD 压缩文件)作为一个单独的文件放入新 ZIP 文件中,同时对新 ZIP 文件举行加密。
方法测试:
  1.   public static void main(String[] args) {
  2.         String directoryPath = "D:\\桌面\\AAA"; // 替换为你本地的路径
  3.         String backupDirectoryPath = "D:\\桌面\\备份"; // 替换为你的备份路径
  4.         String password = "ssssssss.";
  5.         long maxSize = 1024L * 1024L * 1024L; // 1GB
  6.         try {
  7.             Files.createDirectories(Paths.get(backupDirectoryPath));
  8.             // 首先收集所有要处理的文件
  9.             List<Path> filesToProcess = new ArrayList<>();
  10.             Files.walkFileTree(Paths.get(directoryPath), new SimpleFileVisitor<>() {
  11.                 @Override
  12.                 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
  13.                     String fileName = file.getFileName().toString().toLowerCase();
  14.                     if (fileName.endsWith(".zip") && Files.size(file) <= maxSize) {
  15.                         filesToProcess.add(file);
  16.                     }
  17.                     return FileVisitResult.CONTINUE;
  18.                 }
  19.                 @Override
  20.                 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
  21.                     Path backupDir = Paths.get(backupDirectoryPath, dir.toString().substring(directoryPath.length()));
  22.                     Files.createDirectories(backupDir);
  23.                     return FileVisitResult.CONTINUE;
  24.                 }
  25.             });
  26.             // 然后处理收集到的文件
  27.             int totalFiles = filesToProcess.size();
  28.             for (int i = 0; i < totalFiles; i++) {
  29.                 Path file = filesToProcess.get(i);
  30.                 Path backupFile = Paths.get(backupDirectoryPath, file.toString().substring(directoryPath.length()));
  31.                 Files.createDirectories(backupFile.getParent());
  32.                 Files.copy(file, backupFile, StandardCopyOption.REPLACE_EXISTING);
  33.                 ZipEncryptionUtil.createEncryptedZipWithOldZip(file.toFile(), password);
  34.                 // 记录进度
  35.                 System.out.printf("Processed file (%d/%d): %s%n", i + 1, totalFiles, file.toString());
  36.             }
  37.         } catch (IOException e) {
  38.             e.printStackTrace();
  39.         }
  40.     }
复制代码
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表