Search code examples
ruby-on-railsruby-on-rails-4attr-encrypted

How to search an encrypted field in attr_encrypted


I have set up attr_encrypted in my app with individual 'iv's for every record.

# Fields
User.e_name
User.e_name_iv

I am trying to search the User table for a known name. I've tried:

User.find_by_name("Joe Bloggs") # undefined method "find_by_name" for Class
User.where("name = ?", "Joe Bloggs").first # column "name" does not exist
User.where(:e_name => User.encrypt_name("Joe Bloggs"))  # must specify an iv

How can I find a record by its name?


Solution

  • While it is possible to do some searching, it's not very practical. you'll have to potentially iterate through every record trying each respective IV until you have an exact match, depending on the number of records you have this will not be very practical.

    Have you read the readme? https://github.com/attr-encrypted/attr_encrypted#things-to-consider-before-using-attr_encrypted

    Searching, joining, etc

    While choosing to encrypt at the attribute level is the most secure solution, it is not without drawbacks. Namely, you cannot search the encrypted data, and because you can't search it, you can't index it either. You also can't use joins on the encrypted data. Data that is securely encrypted is effectively noise. So any operations that rely on the data not being noise will not work. If you need to do any of the aforementioned operations, please consider using database and file system encryption along with transport encryption as it moves through your stack.