Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

md5 or urlsafe_base64 or other for creating an auth_token

I have a rails app that we use user_id and write to a session variable (which goes as a cookie). I will be using the same token for browsers and mobile platforms.

What is the preferred way of generating an auth token? I have seen:

token = Digest::MD5.hexdigest('some-value') # this
token = SecureRandom.urlsafe_base64 # and this
token = SecureRandom.hex # and this

Is there a significant reason to use one over the other?

thx in advance

like image 946
timpone Avatar asked Dec 07 '25 03:12

timpone


1 Answers

Outside of the context of Rails (since we're talking general web application security here), it's pretty easy to discern.

So, using MD5, you have two methods. Either with a fixed input, or a random one. For the sake of this discussion, any input that includes a random component (like the username with a random attribute appended) is considered random.

The fixed input method is not good. The reason is that it's eventually going to be predictable to some extent. If an attacker can predict his/her token (learn how it was generated), (s)he can use that to attack other tokens. In other words, bad day for everyone.

The random input method is really no different from the pure random token method, with the exception that part of the input is not random.

So I would suggest going with a pure random token. Either base64 or hex is fine, but you should have at least 128 bits of randomness in the token (16 characters), and more if you can. A good base is 256 bits of randomness, which in base64 is 43 characters...

like image 108
ircmaxell Avatar answered Dec 08 '25 18:12

ircmaxell