如何在 Ruby 中生成受密码保护的 zip 文件?

问题描述 投票:0回答:1

基本档案创建工作如下(使用 rubyzip)

Zip::File.open(zipfile_name, create: true) do |zipfile|
  input_filenames.each do |filename|
    zipfile.add(filename, File.join(folder, filename))
  end
end

好吧,我不久前就可以使用了...但现在我需要创建一个受密码保护的 zip。为此,文档有:

enc = Zip::TraditionalEncrypter.new('password')
buffer = Zip::OutputStream.write_buffer(encrypter: enc) do |output|
  output.put_next_entry("my_file.txt")
  output.write my_data
end

我不太明白如何与第一种方法结合使用(迭代文件列表)。

在我的情况下,密码也是可选的 - 用户可以选择存档是否受密码保护。我想避免在每种情况下都使用完全不同的代码。

ruby zip
1个回答
0
投票

如您所见,默认情况下加密器是

nil

但是如果需要的话你可以动态传递它

我建议这样的方法:

require "zip"

def zipfile(filenames:, zip_filename:, password: nil)
  # If password was passed, intitialize encrypter
  encrypter = Zip::TraditionalEncrypter.new(password) if password

  # Create buffer, it is the object like StringIO
  # Pass encrypter there, it will be nil if no password
  buffer = Zip::OutputStream.write_buffer(encrypter: encrypter) do |out|
    Array(filenames).each do |filename|
      # Create file inside zip archive
      out.put_next_entry(File.basename(filename))
      # And fill with file content
      out.write File.read(filename)
    end
  end

  # Write result to the zip file
  File.open(zip_filename, "w") { |zipfile| zipfile.write(buffer.string) }
end

当然您可以根据需要修改它或创建单独的实体

现在您可以调用此方法传递字符串或文件名数组,传递/不传递密码

zipfile(filenames: ["1.txt", "2.txt"], zip_filename: "new.zip", password: "123456")
zipfile(filenames: "/Users/abc/111.txt", zip_filename: "/Users/abc/111.zip")

据我所知,这是 rubyzip 3.0 的相当新的功能,您需要指定此版本(例如在

Gemfile
中)

# Gemfile
source "https://rubygems.org"

gem "rubyzip", "3.0.0.alpha"

并在该版本的上下文中运行脚本,比方说

bundle exec ruby zipper.rb
© www.soinside.com 2019 - 2024. All rights reserved.