Home > database >  Rails - decrypt attr_encrypted manually
Rails - decrypt attr_encrypted manually

Time:03-18

I have a model named Contact which has sensitive information like user's mobile number and email. So I am using the gem attr_encrypted and the columns mobile_number and email are encrypted and stored by default.

While retrieving the records, the mobile_number and email are by default decrypted and this is the gem's behaviour.

Contact.first.email => decypted email is returned

I am storing the encryption key and version in another table called client_encryption.

So whenever I call Contact.first.email, two queries are fired, one to fetch Contact and the other to fetch the encryption key which is expected.

I am currently generating a CSV for all the contacts I have (more than 1 Million). So inside CSV generation, every time I call contact.email, the query to fetch the encryption key is also fired (so 1 Million times the same query is fired).

How can I avoid running the encryption key fetch query? I can manually decrypt the email but not sure how can I do it because encryption is done by the gem.

CodePudding user response:

We can simply use the advantage of decrypt method.

Contact.decrypt_#{encrypted_column_name}(encrypted_value, key: encryption_key)

In my case it has to be

Contact.decrypt_email(encrypted_email, key: encryption_key)

So every time inside my loop, instead of calling

contact.email (which will call query to fetch encryption key), I will simply call decrypt method with the encryption_key that is already cached. 
  • Related