文件打成zip包,并且加密

要用到 gem 'zipruby'

    Zip::Archive.open(save_file_name.zip, Zip::CREATE) do |ar|
        ar.add_file(zip_file_name) 
    end
    Zip::Archive.encrypt(save_file_name.zip, 'password')


之前使用过“rubyzip”这个gem,能压缩打包,但是不能加密。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用Java的ZipOutputStream类和Java的加密库来实现文件压缩和加密。下面是一个示例代码,演示如何压缩文件并对其进行加密: ```java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; 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 ZipEncryptExample { public static void main(String[] args) { String sourceFile = "path/to/source/file"; String zipFile = "path/to/output/zip/file"; String password = "your_password"; try { // 创建ZipOutputStream对象 FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos); // 创建加密Cipher对象 Cipher cipher = Cipher.getInstance("AES"); SecretKeySpec secretKey = new SecretKeySpec(password.getBytes(), "AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); // 添加文件zip文件中 addToZip(sourceFile, sourceFile, zos, cipher); // 关闭流 zos.close(); fos.close(); System.out.println("压缩并加密完成!"); } catch (Exception e) { e.printStackTrace(); } } private static void addToZip(String fileName, String sourceFile, ZipOutputStream zos, Cipher cipher) throws Exception { File file = new File(sourceFile); FileInputStream fis = new FileInputStream(file); // 创建ZipEntry对象,并设置文件ZipEntry zipEntry = new ZipEntry(fileName); zos.putNextEntry(zipEntry); // 创建CipherOutputStream对象,将加密的数据写入ZipOutputStream 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(); } } ``` 在上面的示例代码中,您需要将`sourceFile`替换为要压缩的文件的路径,`zipFile`替换为输出的ZIP文件路径,`password`替换为您想要使用的加密密码。代码会将指定的文件压缩成ZIP文件,并使用AES算法对其进行加密。 请确保您已经含了Java的加密库,通过`import javax.crypto.Cipher`和`import javax.crypto.CipherOutputStream`导入相应的类。 请注意,加密和解密文件需要相同的密码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值