Rails 7.0 adds encryption to Active Record

Adding an additional security layer in an application that handles sensitive data is definitely a necessity. Rails 7.0 introduces at-work encryption for sensitive attributes which protects against the exposure of personal information in the event a malicious party gains access to the database and is in a position to get a snapshot of it, as well as that of the application logs. The addition of encrypted attributes in ActiveRecord models is an extraction from HEY.

Before Rails 7.0

gem "attr_encrypted" could be used to generate virtual attributes that transparently encrypt and decrypt attributes.

The declaration would be something like this and would differ depending on the use case:

1
2
3
class User
  attr_encrypted :ssn, key: 'This is a key that is 256 bits!!'
end

For more information on how this worked and it’s set up, read the description and setup instructions here.

After Rails 7.0

To get started, run bin/rails db:encryption:init to generate a random key set that is added to the Rails credentials.

The declaration of encrypted attributes is then done as below:

1
2
3
class Person < ApplicationRecord
  encrypts :name
end

The library has the attributes declared at the model level backed with a column of the same name. By default, the data is encrypted using AES-GCM with a 256-bits key and a non-deterministic approach before saving and will be decrypted when the data is retrieved. The encryption layer exists between the application and the database.

The library also comes packed with great additional features such as:

More on how this library works and its implementation can be found here.