What is Encryption and Why do We Encrypt

Encryption is the process of scrambling data to make it unreadable to humans.

None

It ensures the privacy of sensible data and increases its security by rendering it unusable in the event of a data breach.

Furthermore, it helps to prevent data tampering when it is transmitted across the Internet, and it is used to authenticate a website with SSL certificates.

Lastly, it is also mandatory to comply with government and industry regulations like GDPR.

Before Rails 7

In previous versions of Rails, software developers had to rely on third-party Ruby gems to encrypt attributes.

For example, attr_encrypted has been around for quite some years and has built its own legion of followers. And I can see why! It's fairly easy to encrypt a model's field with it:

After Rails 7

The current Ruby on Rails edge version includes this functionality out of the box and it's that easy to set up as well.

We just need to add a key to our config/credentials.yml.enc with:

$ rails db:encryption:init

And declare the field to encrypt in the model:

Rails will encrypt and decrypt this attribute when saving to and reading from the database.

article = Article.create title: "Encrypt it all!"
article.title # => "Encrypt it all!"

Deterministic and Non-Deterministic encryption

Deterministic encryption means that the same content will always produce the same resulting cipher. On the other hand, non-deterministic encryption makes it so that the same content results in different ciphers.

Rails' default is to use a non-deterministic approach since it increases the security of the data stored. Unfortunately, it also renders the data "unqueryable".

Therefore, if you want to query data on the encrypted field you'll need to explicitly use the deterministic way:

Article.find_by_title("My title") # This will fail
Article.find_by_author_email("author@email.com") # This works

Conclusion

Hope you find this quick guide helpful. Let me know your thoughts on it in the comments and please share it in your network.

Thanks for reading!

References