Generating Encrypted Zip files in Rails

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:

Here are other uses:

  1. 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.

  2. 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 app/views/posts/index.html.erb.

1
2
3
# app/views/posts/index.html.erb

<%= link_to "Export Zip", posts_path(format: 'zip') %>

In 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!