Encrypt & Decrypt Files - Ruby on Rails

Posted by Panos Matsinopoulos on 28/Apr/2024 (06:41)
Hero Image by DESPOINA MATSINOPOULOU from Pixabay

Encrypting & Decrypting using Ruby On Rails Own Utilities

Introduction

Hello my friends!

Today I am presenting to you an easy way for you to encrypt and decrypt files using Ruby on Rails own utilities.

We know that RoR offers the ability to store secrets encrypted inside the file config/credentials.yml.enc, as it is described in Rails Guides - Security - Environmental Security. This facility uses the ENV["RAILS_MASTER_KEY"] or the key stored inside the file config/master.key to encrypt and decrypt the file config/credentials.yml.enc.

But, can use the internals of this facility to encrypt and decrypt another file in our RoR project repository? Or maybe we want to encrypt and decrypt a piece of text.

This is how we can do it:

ActiveSupport::EncryptedFile

By looking into the RoR source code, I have found this class here, the ActiveSupport::EncryptedFile.

Encryption

So, here is how I can use it to encrypt a file in my repository:

I encrypt the file secret_content_file.txt. This will generate a new file with name secret_content_file.txt.enc.

Decryption

The decryption is done with a piece of code like this:

The above decrypts the file secret_content_file.txt.enc. It generates a new file with name secret_content_file.txt.

Things to Keep In Mind

The above snippets use the master key, either in the config/master.key file or in the environment variable RAILS_MASTER_KEY. But, you can easily adapt it to use a different key if you want.

Make sure that you don't check in your clear versions of the files, only the encrypted ones.

Finally, make sure that you don't lose the key with which you encrypt/decrypt. You will not be able to recover your encrypted files contents.

Closing Note

That was a quick tip on how you can encrypt/decrypt files in a Ruby on Rails project using the standard RoR utilities.

By the way, I used this technique in one of my projects to encrypt the Terraform state files which I wanted to commit (encrypted) in the a remote git repository.

Thank you.

Panos Matsinopoulos


If you liked this post, you can buy me a cup of coffee to keep me company when writing the next one.