温馨提示×

java怎么生成zip文件加密

小亿
120
2023-12-13 14:06:26
栏目: 编程语言

要生成一个加密的zip文件,可以使用Java的ZipOutputStream类和密码输入流。

下面是一个示例代码,演示了如何生成一个加密的zip文件:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;

public class EncryptZipFile {
    public static void main(String[] args) {
        String sourceFile = "source.txt"; // 要加密的文件路径
        String zipFile = "encrypted.zip"; // 加密后的zip文件路径
        String password = "password"; // 加密密码

        try {
            FileOutputStream fos = new FileOutputStream(zipFile);
            ZipOutputStream zos = new ZipOutputStream(fos);

            // 创建一个AES加密算法的密钥
            SecretKeySpec secretKey = new SecretKeySpec(password.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");

            // 加密模式
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            FileInputStream fis = new FileInputStream(sourceFile);
            ZipEntry zipEntry = new ZipEntry(sourceFile);
            zos.putNextEntry(zipEntry);

            // 创建一个加密输出流
            CipherOutputStream cos = new CipherOutputStream(zos, cipher);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) >= 0) {
                cos.write(buffer, 0, length);
            }

            cos.close();
            fis.close();
            zos.closeEntry();

            zos.close();

            System.out.println("加密成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在上面的代码中,使用了AES加密算法和密码作为密钥来加密文件。将源文件的内容写入CipherOutputStream,它会自动加密数据并写入ZipOutputStream中。最后,关闭流并保存加密后的zip文件。

请注意,这只是一个简单的示例,如果要进行更严格的文件加密,请参考使用更安全的加密算法和相关配置。

0