Blowfish in the URL

Posted by Jonas Elfström Thu, 15 Nov 2007 21:38:00 GMT

Sometimes you do not want to show the database id for a row in the URL. The reason could be that you do not want someone to be able to scan through all the data.

One solution is to use GUID's but they have drawbacks and one of them is that they add a considerable length to the URL. The shortest URL-safe representation of a GUID I've seen is 22 characters but usually they are 36 characters.

Depending on how your id's are implemented a much shorter way could be to simply to encrypt them.

Here's a Ruby-example that Blowfish encrypts, Base64 encodes and URL-encodes an integer value. You can get crypt as a gem:

gem install crypt

1
2
3
4
5
6
7
8
9
10
11
require 'rubygems'
require 'crypt/blowfish'
require 'Base64'
blowfish = Crypt::Blowfish.new("A key up to 56 bytes long")
plainId=123456
encrypted = blowfish.encrypt_block(plainId.to_s.ljust(8))
idForURL = URI.escape((Base64.encode64(encrypted).strip))
decryptedId = blowfish.decrypt_block(  
                          Base64.decode64(  
                          URI.unescape(idForURL))).
                          strip.to_i


The .ljust(8) is because Blowfish is a 64-bit block cipher and the Ruby-implementation does not pad the data itself.

The id in the URL in this case would be c2PSXWgky40=. Its 12 characters long (11 if you skip the equal sign) and that's 10 or 24 characters shorter than a GUID. Also there is zero percent chance of collusion and if you want to you can even decrypt it.

This is not a super safe implementation but if you start your id's at a random and not too low number you are making it a bit harder for someone to crack the 56-bit key. Actually a truly random and at least 64-bit big number would be a better choice as it would have no connection to the true id at all. You would have to check for uniqueness before storing those in the database though.

Posted in Security, Ruby, Cryptography | no comments

Comments

Comments are closed