Skip to content
This repository has been archived by the owner on Apr 7, 2023. It is now read-only.
dougc84 edited this page Sep 14, 2012 · 5 revisions

Requirements

Ruby 1.9.3 w/ Rails 3.1.3. Realistically, it should work on Ruby 1.9.x and Rails 3.1.x, but may work on other configurations. It hasn't been tested.

Installation

Add the following to your gemfile:

gem 'carrierwave_securefile'

...and run the obligatory

bundle

command to install.

Usage

Initializer

Add an initializer in yourapp/config/initializers. Name it carrierwave_securefile.rb. Add the following:

CarrierWave::SecureFile.configure do |config|
	# if using anything except AES:   
	config.cypher = ("Your cypher code here")[0..55]
	# Optional: specify the encrpytion_type.  This can be blowfish, rijndael, or gost.
	# config.encryption_type = "blowfish"

	# if using AES:
	config.encryption_type = :aes
	config.aes_key = "256 bit key here"
	config.aes_iv = "iv here"
end

The cypher must be no longer than 56 characters.

For AES, the aes_iv will remain consistent throughout all file encryptions. You can use the aes_key value to set a default key, but if you add an aes_key attribute to your uploader model, it will generate a random one on every file upload :)

Uploader

process :secure_file
def secure_file
	CarrierWave::SecureFile::Uploader.secure_file( model, self.file.path.to_s )
end

This sends the model data (typically nil, but differentiates between uploads and downloads) as well as the current file name (self.to_s - which is needed to encrypt the file).

Downloader

You will not be able to call YourUploader.asset_file (or whatever you chose with your CarrierWave uploader) directly. Create a new get controller action, and use the following code. Change where appropriate. Assumed using an uploader named UserFileUploader, and a model called UserFile.

def file
	# get the decrypted file from the server.  needs the uploader model, the record the file is
	# attached to in your ORM, and the actual field name (as a symbol or a string) that the file
	# is stored.
	decrypted_file = CarrierWave::SecureFile::Downloader.call( UserFileUploader, UserFile.find(params[:id]), :file_field )
	# decrypted file is a hash set up as follows:
	# decrypted_file[:file] - the decrypted file, hopefully saved in a tmp path, not somewhere
	# public-facing.
	# decrypted_file[:content_type] - returns content type, if available.
	# send the file to the user:
	send_file decrypted_file[:file], :content_type => decrypted_file[:content_type]
	# then immediately destroy the file.  You don't want an unencrypted file saved on your
	# server... or do you?
	File.unlink decrypted_file[:file]
end

And that's it! You're good to go.