zip加密加密解密

今天项目需要对文件或文件夹进行加密压缩,通过了解目前可以实现的有jdk自带的以及一些第三方的实现方式,了解到了zip4j的强大,并且参考了网上的用法,亲测有效!

1:引入maven依赖

<!-- https://mvnrepository.com/artifact/net.lingala.zip4j/zip4j -->
   <dependency>
      <groupId>net.lingala.zip4j</groupId>
      <artifactId>zip4j</artifactId>
      <version>1.3.2</version>
   </dependency>

2:工具类


import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.FileHeader;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Description: zip工具类(加密压缩和解密)
 * @date 2019/4/19 11:50
 */
public class ZipUtil {


    /**
     * 使用给定密码解压指定的ZIP压缩文件到指定目录
     * <p>
     * 如果指定目录不存在,可以自动创建,不合法的路径将导致异常被抛出
     *
     * @param dest   解压目录
     * @param passwd ZIP文件的密码
     * @return 解压后文件数组
     * @throws ZipException 压缩文件有损坏或者解压缩失败抛出
     */
    public static File[] unzip(File zipFile, String dest, String passwd) throws ZipException {
        ZipFile zFile = new ZipFile(zipFile);
        zFile.setFileNameCharset("GBK");
        if (!zFile.isValidZipFile()) {
            throw new ZipException("压缩文件不合法,可能被损坏.");
        }
        File destDir = new File(dest);
        if (destDir.isDirectory() && !destDir.exists()) {
            destDir.mkdir();
        }
        if (zFile.isEncrypted()) {
            zFile.setPassword(passwd.toCharArray());
        }
        zFile.extractAll(dest);

        List<FileHeader> headerList = zFile.getFileHeaders();
        List<File> extractedFileList = new ArrayList<File>();
        for (FileHeader fileHeader : headerList) {
            if (!fileHeader.isDirectory()) {
                extractedFileList.add(new File(destDir, fileHeader.getFileName()));
            }
        }
        File[] extractedFiles = new File[extractedFileList.size()];
        extractedFileList.toArray(extractedFiles);
        return extractedFiles;
    }


    /**
     * 使用给定密码压缩指定文件或文件夹到指定位置.
     * <p>
     * dest可传最终压缩文件存放的绝对路径,也可以传存放目录,也可以传null或者"".<br />
     * 如果传null或者""则将压缩文件存放在当前目录,即跟源文件同目录,压缩文件名取源文件名,以.zip为后缀;<br />
     * 如果以路径分隔符(File.separator)结尾,则视为目录,压缩文件名取源文件名,以.zip为后缀,否则视为文件名.
     *
     * @param src         要压缩的文件或文件夹路径
     * @param dest        压缩文件存放路径
     * @param isCreateDir 是否在压缩文件里创建目录,仅在压缩文件为目录时有效.<br />
     *                    如果为false,将直接压缩目录下文件到压缩文件.
     * @param passwd      压缩使用的密码
     * @return 最终的压缩文件存放的绝对路径, 如果为null则说明压缩失败.
     */
    public static String zip(String src, String dest, boolean isCreateDir, String passwd) {
        File srcFile = new File(src);
        dest = buildDestinationZipFilePath(srcFile, dest);
        ZipParameters parameters = new ZipParameters();
        parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);           // 压缩方式
        parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);    // 压缩级别
        if (!StringUtils.isEmpty(passwd)) {
            parameters.setEncryptFiles(true);
            parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD); // 加密方式
            parameters.setPassword(passwd.toCharArray());
        }
        try {
            ZipFile zipFile = new ZipFile(dest);
            if (srcFile.isDirectory()) {
                // 如果不创建目录的话,将直接把给定目录下的文件压缩到压缩文件,即没有目录结构
                if (!isCreateDir) {
                    File[] subFiles = srcFile.listFiles();
                    ArrayList<File> temp = new ArrayList<File>();
                    Collections.addAll(temp, subFiles);
                    zipFile.addFiles(temp, parameters);
                    return dest;
                }
                zipFile.addFolder(srcFile, parameters);
            } else {
                zipFile.addFile(srcFile, parameters);
            }
            return dest;
        } catch (ZipException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 构建压缩文件存放路径,如果不存在将会创建
     * 传入的可能是文件名或者目录,也可能不传,此方法用以转换最终压缩文件的存放路径
     *
     * @param srcFile   源文件
     * @param destParam 压缩目标路径
     * @return 正确的压缩文件存放路径
     */
    private static String buildDestinationZipFilePath(File srcFile, String destParam) {
        if (StringUtils.isEmpty(destParam)) {
            if (srcFile.isDirectory()) {
                destParam = srcFile.getParent() + File.separator + srcFile.getName() + ".zip";
            } else {
                String fileName = srcFile.getName().substring(0, srcFile.getName().lastIndexOf("."));
                destParam = srcFile.getParent() + File.separator + fileName + ".zip";
            }
        } else {
            createDestDirectoryIfNecessary(destParam);  // 在指定路径不存在的情况下将其创建出来
            if (destParam.endsWith(File.separator)) {
                String fileName = "";
                if (srcFile.isDirectory()) {
                    fileName = srcFile.getName();
                } else {
                    fileName = srcFile.getName().substring(0, srcFile.getName().lastIndexOf("."));
                }
                destParam += fileName + ".zip";
            }
        }
        return destParam;
    }


    /**
     * 在必要的情况下创建压缩文件存放目录,比如指定的存放路径并没有被创建
     *
     * @param destParam 指定的存放路径,有可能该路径并没有被创建
     */
    private static void createDestDirectoryIfNecessary(String destParam) {
        File destDir = null;
        if (destParam.endsWith(File.separator)) {
            destDir = new File(destParam);
        } else {
            destDir = new File(destParam.substring(0, destParam.lastIndexOf(File.separator)));
        }
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
    }


//    public static void main(String[] args) throws Exception {
//        String zip = zip("/**/Desktop/aa.txt", null, false, "123456");
//        File zipFile = new File("/**/Desktop/aa.zip");
//        unzip(zipFile,"/**/Desktop/love","123456");
//    }


}

更多zip4j的用法 参考博文 https://blog.csdn.net/djun100/article/details/18007099,本文大部分code来自于该文。

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以使用ZipOutputStream和ZipInputStream来处理zip文件。要加密zip文件,可以使用加密算法对压缩文件中的每个条目进行加密。以下是一个例子: ```java import java.io.*; import java.security.*; import java.util.*; import java.util.zip.*; public class ZipEncryptor { public static void encryptZip(String zipFile, String password) throws IOException, NoSuchAlgorithmException, InvalidKeyException { byte[] buffer = new byte[1024]; ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile)); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile + ".encrypted")); zos.setMethod(ZipOutputStream.DEFLATED); zos.setLevel(Deflater.DEFAULT_COMPRESSION); byte[] key = password.getBytes(); SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, keySpec); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { zos.putNextEntry(new ZipEntry(entry.getName())); int len; while ((len = zis.read(buffer)) > 0) { byte[] encrypted = cipher.update(buffer, 0, len); zos.write(encrypted, 0, encrypted.length); } byte[] finalEncrypted = cipher.doFinal(); zos.write(finalEncrypted, 0, finalEncrypted.length); zos.closeEntry(); } zis.close(); zos.close(); } public static void decryptZip(String zipFile, String password) throws IOException, NoSuchAlgorithmException, InvalidKeyException { byte[] buffer = new byte[1024]; ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile)); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile + ".decrypted")); zos.setMethod(ZipOutputStream.DEFLATED); zos.setLevel(Deflater.DEFAULT_COMPRESSION); byte[] key = password.getBytes(); SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, keySpec); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { zos.putNextEntry(new ZipEntry(entry.getName())); int len; while ((len = zis.read(buffer)) > 0) { byte[] decrypted = cipher.update(buffer, 0, len); zos.write(decrypted, 0, decrypted.length); } byte[] finalDecrypted = cipher.doFinal(); zos.write(finalDecrypted, 0, finalDecrypted.length); zos.closeEntry(); } zis.close(); zos.close(); } } ``` 为了加密zip文件,可以调用`encryptZip`方法,并将zip文件路径和密码作为参数传递。文件将被加密并写入同一目录下的`.encrypted`文件中。要解密加密zip文件,可以调用`decryptZip`方法,并将加密文件路径和密码作为参数传递。文件将被解密并写入同一目录下的`.decrypted`文件中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值