Generating encrypted zip files in Rails is an excellent way to secure sensitive data, and it’s easy to do.
The benefits of generating encrypted zip files include:
Increased security for the data you’re storing
Ease of use for your users
Simplified process for uploading files or sending them via email (no need to open an attachment)Sometimes you need to create password-protected zip files in Ruby on Rails. The idea is to create a CSV file first and then add it to a zip file that will be encrypted. For instruction on generating a CSV file, please read this post.
Here are other uses:
You can store sensitive data like passwords or credit card numbers in an encrypted zip file, and then send it off over email or store it on Dropbox to share with customers.
The zip file can be downloaded by anyone who has access to the URL (or link), but only someone with the password will be able to open it up and see what’s inside.
First, add the necessary gems.
1 2 3 4 # Gemfile gem 'rubyzip', '>= 1.0.0' gem 'zip-zip'
Now add a button to export zip files in
1 2 3 # app/views/posts/index.html.erb <%= link_to "Export Zip", posts_path(format: 'zip') %>
app/controllers/posts_controller.rb, put the following lines of code:
1 2 3 4 5 6 7 8 9 10 11 12 # app/controllers/posts_controller.rb format.zip do compressed_filestream = Zip::OutputStream.write_buffer(::StringIO.new(''), Zip::TraditionalEncrypter.new('admins_only')) do |zos| # Users zos.put_next_entry 'posts.csv' posts = Post.to_csv zos.print posts end compressed_filestream.rewind send_data compressed_filestream.read, filename: 'data.zip' end
There you have it! Happy zipping!