Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to obfuscate numerical IDs in an application

Given I've got a site where most of the resources have numerical IDs (i.e. user.id question.id etc.) but that like the Germans looking back on WWII I'd rather not reveal these to the observers, what's the best way to obfuscate them?

I presume the method is going to involve the .to_param and then some symmetric encryption algorithm but I'm not sure what's the most efficient encryption to do and how it'll impact lookup times in the DB etc.

Any advice from the road trodden would be much appreciated.

like image 597
Peter Nixey Avatar asked Jul 08 '11 09:07

Peter Nixey


1 Answers

I usually use a salted Hash and store it in the DB in an indexed field. It depends on the level of security you expect, but I use one salt for all.

This method makes the creation a bit more expensive, because you are going to have an INSERT and an UPDATE, but your lookups will be quite fast.

Pseudo code:

class MyModel << ActiveRecord::Base

  MY_SALT = 'some secret string'

  after_create :generate_hashed_id

  def to_param
    self.hashed_id
  end

  def generate_hashed_id
    self.update_attributes(:hashed_id => Digest::SHA1.hexdigest("--#{MY_SALT}--#{self.id}--"))
  end

end

Now you can look up the record with MyModel.find_by_hashed_id(params[:id]) without any performance repercussions.

like image 91
Wukerplank Avatar answered Oct 22 '22 03:10

Wukerplank