1

In a login system I'm doing, I'm using a per-user, per-device randomly generated cookie token. A part of the script looks like this:

// Generate current device's token
$token = substr(bin2hex(mcrypt_create_iv(200)), 0, 60);

// Include this device's token
$STH = $userDB->prepare("INSERT INTO devices (user_id, token, active) VALUES (?, ?, 1)");
$Res = $STH->execute(array($Id, $token));

if (!$Res)
  throw new Exception("Couldn't store the device in the database");

// To keep users logged in between sessions
$Cookie->email = $email;
$Cookie->token = $token;

However, this implies that if the database was stolen, the attacker would be able to log in as anyone by changing the cookies. This is an issue I want to avoid. I know that sha256 is not valid for general password hashing. However, from the string this comes from,

$token = substr(bin2hex(mcrypt_create_iv(200)), 0, 60);

Is it secure to store a sha256 hash of the high entropy token in the database? Or should I be using the more expensive bcrypt, as with the passwords?

1

So long as your token is sufficiently long enough, I think you would be OK using simply SHA256. I'm not very familiar with PHP, but it looks like you are creating tokens of length 200, which would be more than sufficient. The reason that I would think that SHA256 would be OK is that the search space for a length token is so gigantic that it doesn't really matter how fast the hashing function is. There is no chance that it will be brute forced in any of our lifetimes.

However, from the programming side of things, I might still recommend using bcrypt. I'm not sure about the PHP implementation, but Bcrypt hashing is generally less difficult to screw up that straight SHA256 hashing, which makes it less likely for you to have bugs in your system. If you are using bcrypt elsewhere for password based authentication, then using it consistently instead of having two different methods for hashing makes your system less complicated and therefor also less likely to have critical bugs. If you are worried about speed, be careful not to optimize your system too soon. Implement it with bcrypt first and then do some profiling of your system. If and only if you identify your token hashing system as slowing down things should you think about using SHA256.

  • The sha256 hash is easier in PHP, however you are right, I'm using already bcrypt so I better stay coherent. The thing with bcrypt (at least for PHP) is that I can change how long it takes for each hash. So I guess now the question would better be, how long it needs to take for each hash. I find 0.5 seconds too high, but I'll ask in another question here, thank you (: – Francisco Presencia Apr 2 '14 at 16:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.