ActiveSupport::MessageEncryptor Rails 5.x

A simple way to encrypt values

Rohit Lingayat
1 min readJul 27, 2020

Overview

MessageEncryptor is a simple way to encrypt values which get stored somewhere you don’t trust. The ciphertext and initialization vector are base64 encoded and returned to you. For more details, you can check out the official ruby doc here

Upgrading from Rails 4 to Rails 5 we also need to take care of ActiveSupport::MessageEncryptor. The behavior of the key is changed in Rails 5 and Ruby 2.4.2 and above.

For example, if you simply want to encrypt and decrypt the values in Rails 4 and ruby 2.2.0

snippet encrypt and decrypt using ActiveSupport Message Encryptor

Now in rails, 5 key should be 32 bytes only, so it is kind of breaking change when you upgrade rails 4 to rails 5.

To solve this issue in Rails 5.X and Ruby 2.4.2 and above you need to send 32 bytes of the key.

snippet encrypt and decrypt using ActiveSupport Message Encryptor

Hope this small tip helps you to save your time. cheers 🍻

References:

--

--

Rohit Lingayat

Ruby on Rails | React | AWS | Solr | JQuery | Nodejs | Typescript