如何在rails中模糊我的记录的ID? [英] How do I obfuscate the ids of my records in rails?
问题描述
例如:一个典型的路径可能看起来像 http:// domain / records / 1 ,因此人们很容易推断出网站获得的流量,如果他们只是创建一个新纪录。
我使用的一个解决方案是用一个salt来散列id,但由于我不确定该函数是否是双射的,所以我最终将它存储我的数据库中的另一列,并双重检查唯一性。
我正在考虑的另一个选择是生成一个随机散列并将其存储为另一列。如果它不是唯一的...只是生成另一个。
这是最好的方法是什么?
使用内置的OpenSSL库来加密和解密您的标识符,这样您只需要在您的模型上覆盖 to_param
。您还需要使用Base64将加密的数据转换为纯文本。我会把它放在一个模块中,以便它可以重用:
require'openssl'
require'base64'
模块obfuscate
def self.included(base)
base.extend self
end
def cipher
OpenSSL :: Cipher :: Cipher.new('aes-256-cbc')
end
def cipher_key
'blah!'
end
$ b b 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
现在你的模型需要看起来像这样:
class MyModel< ActiveRecord :: Base
include obfuscate
def to_param
encrypt id
end
end
然后在你的控制器中,当你需要通过加密的id找到一个记录时,你会使用这样的:
MyModel.find MyModel.decrypt(params [:id])
$ b b
如果您希望加密/解密 而不 将它们存储在数据库中,这可能是最简单的方法。
I'm trying to figure out how to obfuscate the ids of my records in rails.
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.
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?
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
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])
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屋!