Rails - 手动解密 attr_encrypted

Rails - decrypt attr_encrypted manually

我有一个名为 Contact 的模型,其中包含用户的手机号码和电子邮件等敏感信息。所以我使用 gem attr_encrypted 列 mobile_number 和电子邮件默认加密和存储。

检索记录时,mobile_number 和电子邮件默认解密,这是 gem 的行为。

Contact.first.email => decypted email is returned

我将加密密钥和版本存储在另一个名为 client_encryption 的 table 中。

因此,每当我调用 Contact.first.email 时,都会触发两个查询,一个用于获取联系人,另一个用于获取预期的加密密钥。

我目前正在为我拥有的所有联系人(超过 100 万)生成 CSV。所以在 CSV 生成中,每次我调用 contact.email,获取加密密钥的查询也会被触发(所以相同的查询被触发了 100 万次)。

如何避免 运行 加密密钥提取查询?我可以手动解密电子邮件,但不确定我该怎么做,因为加密是由 gem.

我们可以简单地利用解密方法的优势。

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

在我的例子中它必须是

Contact.decrypt_email(encrypted_email, key: encryption_key)

所以每次在我的循环中,而不是调用

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