java · 2025-09-28 0

java 创建加密的 zip 包

<dependency>
    <groupId>net.lingala.zip4j</groupId>
    <artifactId>zip4j</artifactId>
    <version>2.11.5</version>
</dependency>

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>
@Test
public void testDataSerialize3() throws IOException {
    File file1 = File.createTempFile("abc", ".txt");
    File file2 = File.createTempFile("def", ".txt");
    String zipFilePath = String.format("%s/%s_%s.%s", System.getProperty("java.io.tmpdir"), "temp",
            System.currentTimeMillis(), "zip");

    List<String> filePathList = new ArrayList<>();
    filePathList.add(file1.getAbsolutePath());
    filePathList.add(file2.getAbsolutePath());

    createZipFile(zipFilePath, true, "123456", filePathList);
    File result = new File(zipFilePath);

    file1.deleteOnExit();
    file2.deleteOnExit();
    result.deleteOnExit();

    assertTrue(result.exists());
}

public static void createZipFile(String zipFileName, boolean toEncrypt, String fileSecretKey,
                                 List<String> filePathList) throws IOException {
    List<File> filesToZip = filePathList.stream().filter(Objects::nonNull).map(File::new).collect(Collectors.toList());

    if (filesToZip.isEmpty()) {
        // 若没有可添加的文件,创建空 zip 文件
        Files.createFile(Paths.get(zipFileName));
        return;
    }

    try (ZipFile zipFile = new ZipFile(zipFileName, (toEncrypt && fileSecretKey != null) ? fileSecretKey.toCharArray() : null)) {
        // 往 zipFile 添加文件,会创建 zip 文件
        if (!toEncrypt) {
            zipFile.addFiles(filesToZip);
            return;
        }
        ZipParameters zipParameters = new ZipParameters();
        zipParameters.setEncryptFiles(true);
        // ubuntu 可能无法识别 AES 加密
        // zipParameters.setEncryptionMethod(EncryptionMethod.AES);
        // zipParameters.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_256);
        // 改为传统加密(ZipCrypto),兼容 Info-ZIP
        zipParameters.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD);

        zipFile.addFiles(filesToZip, zipParameters);
    }
}