在ruby中存储可解密密码的安全方法

Sam*_*Sam 3 ruby encryption ruby-on-rails ruby-on-rails-4

我想以安全的方式将一些密钥以加密形式存储在数据库中.同时我需要在代码中的某处使用非加密(原始)形式的密钥.我打算用PBKDF2进行密码散列PBKDF2.是否可以使用PBKDF2以加密形式解密存储在数据库中的密钥.或者是否有任何简单安全的程序?

Pat*_*ity 7

Passwords and secret keys are usually stored in their hashed form. That means they are processed through a hash function before being saved to the database. A good hash function such as bcrypt has the following properties:

  • it produces the same output for the same input
  • it produces very different output for different inputs
  • its output is not distinguishable from random
  • it is not reversible

The last property has a very important security implication: when someone gets access to the database, they cannot recover the original keys because the hash function is not reversible, especially when the hash is salted to prevent attackers from using rainbow tables.

That means if you want to recover the keys later on, you have to save them in encrypted (not hashed) form. An encryption function has similar properties like a hash function, with the key difference that it is in fact reversible. For this decryption step you need a key, which needs to be stored somewhere.

You could store the the key in your application config but that would mean that if someone gains access to your server, they would be able to retrieve the encryption key and decrypt all the stored keys.

I suggest an alternative approach, which will users allow to retrieve only their own stored keys. It is based on the idea that the keys are encrypted with a user-specific password that only the user knows. Whenever you need to perform an action that needs to store or retrieve the keys, the user is prompted for their password. This way, neither yourself nor an attacker will be able to retrieve them, but your program can access them if the user allows it by entering his password.

  • Store a conventionally hashed user password in the database e.g. using bcrypt
  • Allow users to store additional password with the following procedure:
    • Prompt for user password and keys to store
    • Hash password and compare with database to authenticate
    • Generate salt for each entered key
    • 使用用户输入的密码和salt加密密钥以存储,例如使用AES加密
    • 将salt和加密密钥存储在数据库中
  • 要在以纯文本格式要求它们的操作中检索存储的键:
    • 提示用户密码
    • 哈希密码并与数据库进行比较以进行身份​​验证
    • 从数据库中检索加密的密钥和salt
    • 使用用户密码和salt解密存储的密钥

小心从应用程序日志中删除用户提交的密码;-)