简体   繁体   English

在attr_encrypted列的rails中查询

[英]Querying in rails on attr_encrypted column

I have a ruby on rails app and I am using the attr_encrypted gem to encrypt some user info. 我在rails应用程序上有一个ruby,我使用attr_encrypted gem来加密一些用户信息。 It has a salt and IV so it is 2 way encrypted. 它有盐和IV,所以它是双向加密的。 The gem intercepts dynamic find_by to assist with querying, but that is not a sufficient query for my case as I care about the number of results. gem拦截动态find_by以协助查询,但这对我的情况来说不是一个充分的查询,因为我关心结果的数量。

Is there a way to query the table to return all results that match a given secret ? 有没有办法查询表以返回与给定secret匹配的所有结果?

Here is the example. 这是一个例子。 I have a users table and it has an encrypted secret attribute. 我有一个users表,它有一个加密的secret属性。 The table thus has encrypted_secret , encrypted_secret_iv , and encrypted_secret_salt . 因此,该表具有encrypted_secretencrypted_secret_ivencrypted_secret_salt If a user gave a secret of "abd123", how can I query the table to see how many others have also used "abc123" as their secret? 如果用户给出了“abd123”的秘密,我如何查询该表以查看有多少其他人也使用“abc123”作为他们的秘密?

You could also save an additional secret_hash of the unencrypted secret. 您还可以保存未加密的秘密的其他secret_hash If two records have the same secret then they will have the same secret_hash too. 如果两个记录具有相同的secret那么它们也将具有相同的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 query like this: 之后,您可以像这样查询:

YourModel.by_secret('abd123').count

Warning 警告

Storing MD5 hashes of passwords and other sensitive information is a security risk. 存储密码和其他敏感信息的MD5哈希值存在安全风险。 Even if you cannot tell the plain text secret from a secret_hash , it allows you to tell when users share the same secret . 即使你不能告诉secret_hash的明文secret ,它也可以告诉用户何时共享相同的secret Or - even worse - the MD5 hash might be available in an MD5-reverse-lookup-dictionary. 或者 - 更糟糕的是 - MD5反向查找字典中可能有MD5哈希。

You must carefully trade off this security issue against the benefit of being able to query on that column. 您必须仔细权衡此安全问题,以便能够查询该列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM