You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
If you have been working with Ruby for a while, you would probably be familiar with attr_accessor, attr_reader and attr_writer which provide you with getter and/or setter. These methods are mostly convenient, but if you are required to store sensitive information in the database (i.e. OAuth token), then you will need your own custom getter and setter to protect the sensitive data.
You can make use of the #encrypt_and_sign and #decrypt_and_verify methods available in Rails to encrypt and decrypt data in your custom getter and setter, and here's how you can do it:
Rails has a built-in class MessageEncryptor, which uses OpenSSL::Cipher to perform encryption. Read How does MessageEncryptor works or the source code if you are interested in its inner workings.
If you have been working with Ruby for a while, you would probably be familiar with
attr_accessor
,attr_reader
andattr_writer
which provide you with getter and/or setter. These methods are mostly convenient, but if you are required to store sensitive information in the database (i.e. OAuth token), then you will need your own custom getter and setter to protect the sensitive data.You can make use of the
#encrypt_and_sign
and#decrypt_and_verify
methods available in Rails to encrypt and decrypt data in your custom getter and setter, and here's how you can do it:Feeling paranoid? You can also pass in additional cipher:
Pro-tip: You can get a list of available ciphers with
$ openssl list-cipher-commands
.Testing it is also very simple (with RSpec):
Note that I have used FactoryGirl to perform a
build(:user)
.Alternatively, if you need a lot more features for your encrypted fields, you can also check out attr_encrypted gem.
Remember to secure sensitive information you store in your database! ❤️
Thanks for reading!
@JuanitoFatas ✏️ Jolly Good Code
About Jolly Good Code
We specialise in Agile practices and Ruby, and we love contributing to open source.
Speak to us about your next big idea, or check out our projects.
The text was updated successfully, but these errors were encountered: