Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
Encrypt your data with MessageEncryptor #10
If you have been working with Ruby for a while, you would probably be familiar with
You can make use of the
def token=(value) encrypted_token = cryptor.encrypt_and_sign(value) self[:token] = encrypted_token end def token encrypted_token = self[:token] if encrypted_token.present? cryptor.decrypt_and_verify(encrypted_token) end end private def cryptor ActiveSupport::MessageEncryptor.new(Rails.application.secrets.secret_key_base) end
Feeling paranoid? You can also pass in additional cipher:
ActiveSupport::MessageEncryptor.new( Rails.application.secrets.secret_key_base, cipher: "aes-256-ecb" )
Pro-tip: You can get a list of available ciphers with
Testing it is also very simple (with RSpec):
describe "#token=" do it "saves encrypted token in database" do user = build(:user) user.token = "oauth token" user.save expect(user["token"]).not_to eq("oauth token") end end describe "#token" do it "returns decrypted token upon retrieval" do user = build(:user) user.token = "oauth token" user.save expect(user.reload.token).to eq("oauth token") end end
Note that I have used FactoryGirl to perform a
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!
About Jolly Good Code