如何在 rails 中混淆我的记录的 ID? [英] How do I obfuscate the ids of my records in rails?
问题描述
我正在尝试弄清楚如何在 rails 中混淆我的记录的 id.
I'm trying to figure out how to obfuscate the ids of my records in rails.
例如:一个典型的路径可能看起来像 http://domain/records/1,所以它很漂亮如果人们只是创造一个新记录,他们很容易推断出该网站获得了多少流量.
For example: a typical path might look like http://domain/records/1, so it's pretty easy for people to deduce how much traffic the site is getting if they just create a new record.
我使用的一个解决方案是用盐对 id 进行散列,但由于我不确定该函数是否是双射的,我最终将其存储在数据库的另一列中并仔细检查唯一性.
One solution that I've used is to hash the id with a salt, but since I'm not sure whether that function is bijective, I end up storing it in another column in my database and double check for uniqueness.
我正在考虑的另一个选择是生成一个随机散列并将其存储为另一列.如果它不是唯一的......只需生成另一个.
Another option I was thinking about was generating a random hash and storing that as another column. If it isn't unique ... just generate another one.
这样做的最佳方法是什么?
What's the best way of doing this?
推荐答案
你可以使用内置的 OpenSSL 库来加密和解密你的标识符,这样你只需要覆盖 to_param
你的模型.您还需要使用 Base64 将加密数据转换为纯文本.我会把它放在一个模块中,以便它可以重复使用:
You could use the built-in OpenSSL library to encrypt and decrypt your identifiers, that way you would only need to overwrite to_param
on your models. You'll also need to use Base64 to convert the encrypted data into plain text. I would stick this in a module so it can be reused:
require 'openssl'
require 'base64'
module Obfuscate
def self.included(base)
base.extend self
end
def cipher
OpenSSL::Cipher::Cipher.new('aes-256-cbc')
end
def cipher_key
'blah!'
end
def decrypt(value)
c = cipher.decrypt
c.key = Digest::SHA256.digest(cipher_key)
c.update(Base64.decode64(value.to_s)) + c.final
end
def encrypt(value)
c = cipher.encrypt
c.key = Digest::SHA256.digest(cipher_key)
Base64.encode64(c.update(value.to_s) + c.final)
end
end
所以现在你的模型需要看起来像这样:
So now your models would need to look something like this:
class MyModel < ActiveRecord::Base
include Obfuscate
def to_param
encrypt id
end
end
然后在您的控制器中,当您需要通过加密的 id 查找记录时,您将使用以下内容:
Then in your controller when you need to find a record by the encrypted id, you would use something like this:
MyModel.find MyModel.decrypt(params[:id])
如果您希望加密/解密 ID 而不将它们存储在数据库中,这可能是最简单的方法.
If you're looking to encrypt/decrypt ids without storing them in the database, this is probably the easiest way to go.
这篇关于如何在 rails 中混淆我的记录的 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!