toamitkumar's Code Blog

Ruby, Rails, RubyMotion, Chef, Puppet, Play and others. Opinions expressed here are my own and do not reflect those of my employer.

Encrypting/Decrypting Primary Key Appearing in the URL

| Comments

I paid a small cost for being RESTful.

As RESTful suggests, the GET request will always have the primary key in the URL like:

In the app we have role based access and only admins have access to edit. We made sure that the application is protected and only admins can update an existing record. The so called Security had a different perspective. They were not willing to expose the id(=123). The solution was to encrypt the id.

I came across a good blog here.

Following the same concept:
  1. I added a EncryptDecryptHelper module inside my lib directory. The module has 2 methods.
  2. encrypt -> used OpenSSl Cipher RC4 digest and Base64 encoding of the string for an already defined KEY and IV
  3. decrypt -> used the same KEY and IV to decode the string
  4. Included the module inside my model and over-ride to_param to encrypt the primary key.
  5. Added a before filter method on the application controller to decrypt the primary key.Made sure we are passing objects instead of id while creating links eg:-
  • Do:
<%= link_to 'city', :controller=>‘cities’,:action=>’show’,:id => @city %>

Instead of:

<%= link_to 'city', :controller=>‘cities’,:action=>’show’,:id => %>

The security team is happy now.