Request on rails on attr_encrypted column

I have a ruby ​​on rails application and I use the attr_encrypted stone to encrypt some user information. It has salt and IV, so it is encrypted in 2 directions. The gem intercepts dynamic find_by to help with the query, but this is not a sufficient query for my case, since I care about the number of results.

Is there a way to query a table to return all results that match a given secret ?

Here is an example. I have a users table and it has an encrypted secret attribute. So the table has encrypted_secret , encrypted_secret_iv and encrypted_secret_salt . If the user gave the secret "abd123", how can I query the table to find out how many others also used "abc123" as their secret?

+5
source share
1 answer

You can also save an additional secret_hash secret key. If two entries have the same secret , then they will have the same secret_hash .

Add something like the following to your model:

 scope :by_secret, ->(secret) { where(secret_hash: Digest::MD5.hexdigest(secret) } before_save :generate_secret_hash private def generate_secret_hash self.secret_hash = Digest::MD5.hexdigest(secret) end 

After that, you can request the following:

 YourModel.by_secret('abd123').count 

Warning

Keeping MD5 hashes of passwords and other sensitive information is a security risk. Even if you cannot specify plain secret text with secret_hash , it allows you to tell when users use the same secret . Or - even worse - an MD5 hash may be available in the MD5 reverse lookup dictionary.

You must carefully exchange this security issue in order to be able to query this column.

+2
source

Source: https://habr.com/ru/post/1206597/


All Articles