4

I have a user auth table with a few thousand records containing a password field encrypted by bcrypt-ruby. I've ported the app in to PHP / Yii and need to use this field for authentication.

Is there a way to retrieve this Ruby-created field in PHP?

Verification

By "retrieve" I mean that I need to authenticate user logins using a PHP / Yii app to interpret a DB table with a password field created by bcrypt-ruby in a Rails app.

Bill
  • 93
  • 1
  • 10
  • What do you mean by 'retrieve'? Do you mean 'to encrypt the password using the same algorithm'? If yes then check this http://stackoverflow.com/questions/4795385/how-do-you-use-bcrypt-for-hashing-passwords-in-php – Cheery Feb 17 '12 at 02:12
  • By 'retrieve' I mean that I have a db table with the bcrypted passwords (generated by a Rails app), and I need to verify them using a PHP (Yii) app. – Bill Feb 20 '12 at 23:41

2 Answers2

4

I believe this would solve your problem:

$database_record = "something";   // grab from database
$user_input = 'unicorns';         // take real one from post data
$password = crypt($user_input, '$2a$10$usesomesillystringforsalt$');
// key piece above is the second number, that is the 'work' factor

if (crypt($user_input, $database_record) == $password) {
   echo "Password verified!";
}
else {
    echo 'failed!'; }

This assumes you stored them using BCrypt::Password.create(desired_pass) in Ruby, and were verifying login by BCrypt::Password.new(database_entry) == form_input.

Additionally, to create a new password in your database (i.e. a new user), store the result of

$password = crypt($user_input, '$2a$10$usesomesillystringforsalt$');

Lastly, make sure that you are always using the correct cost factor. The same password with different cost factors will not be equivalent. The default cost factor in bcrypt-ruby is 10 (current version, 3.0.1).

Paul Hoffer
  • 12,606
  • 6
  • 28
  • 37
  • Thanks, this is great. But is there a way to specify a cost factor in PHP crypt? I see there's a way to do it using blowfish, but that's different, no? – Bill Feb 20 '12 at 23:40
  • What's the default cost factor in PHP crypt()? – Bill Feb 20 '12 at 23:56
  • Blowfish is the algorithm used by bcrypt. So using `crypt` with a salt that follows the form of the one above (`$2a$10$usesomesillystringforsalt$`), it will use blowfish (aka bcrypt). At least that is my understanding of PHP's crypt. So to specify the cost, change the 2 digit number between `$2a$` and `$usesomesillystringforsalt$`. I'm more a Ruby person, so if any PHP expert could weigh in here, that would be appreciated. – Paul Hoffer Feb 21 '12 at 08:14
  • Oh. I see. I didn't realize the cost factor was in the crypt code itself. THANKS! – Bill Feb 21 '12 at 22:30
0

You should have a look at the crypt functions at PHP.net

Here you should be able to to what you want if you've followed bcrypt correctly in Ruby.

Andreas Stokholm
  • 1,677
  • 1
  • 12
  • 17