Skip to content

Instantly share code, notes, and snippets.

@tatey
Last active August 21, 2018 22:28
Show Gist options
  • Save tatey/49238def5a25403cf9f09cfed1531606 to your computer and use it in GitHub Desktop.
Save tatey/49238def5a25403cf9f09cfed1531606 to your computer and use it in GitHub Desktop.
AttributeEncrypted is a simple way to encrypt values in the database using the same mechanism as Rails credentials, including the master key.
# AttributeEncrypted is a simple way to encrypt values in the database
# using the same mechanism as Rails credentials, including the master key.
#
# Example:
# class User
# include AttributeEncrypted
#
# attr_accessor :encrypted_secret
# attr_encrypted :secret
# end
#
# user = User.new
# user.secret = "secret123"
# user.encrypted_secret # => "i3xNGZVJCJkU15IfdT..."
module AttributeEncrypted
extend ActiveSupport::Concern
class_methods do
def attr_encrypted(attribute)
define_method(attribute) do
value = public_send("encrypted_#{attribute}")
if value
encryptor.decrypt_and_verify(value)
end
end
define_method("#{attribute}=") do |value|
public_send("encrypted_#{attribute}=", encryptor.encrypt_and_sign(value))
end
end
end
private
def encryptor
Rails.application.credentials.send("encryptor") # Use the same configuration as Rails
end
end
require "rails_helper"
RSpec.describe AttributeEncrypted do
class Model
include AttributeEncrypted
attr_accessor :encrypted_secret
attr_encrypted :secret
end
it "reads nil values as nil" do
model = Model.new
expect(model.encrypted_secret).to be_nil
expect(model.secret).to be_nil
end
it "writes and reads encrypted values" do
model = Model.new
expect(model.encrypted_secret).to be_nil
model.secret = "123secret"
expect(model.encrypted_secret).to_not be_nil
expect(model.secret).to eq("123secret")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment