Salted_password() in php

Hello,

I’m trying to implement a php version of the ruby hashed() and
salted_password() functions in
/vendor/plugins/login_engine/lib/login_engine/authenticated_user.rb

  def self.hashed(str)
    # check if a salt has been set...
    if LoginEngine.config(:salt) == nil
      raise "You must define a :salt value in the configuration for 

the
LoginEngine module."
end
return
Digest::SHA1.hexdigest("#{LoginEngine.config(:salt)}–#{str}–}")[0…39]
end

  def self.salted_password(salt, hashed_password)
    hashed(salt + hashed_password)
  end

def crypt_password
  if @new_password
    write_attribute("salt",

AuthenticatedUser.hashed(“salt-#{Time.now}”))
write_attribute(“salted_password”,
AuthenticatedUser.salted_password(salt,
AuthenticatedUser.hashed(@password)))
end
end

It works great (thanks, by the way). Now php comes along and retrieves
from
the db the “salt” and “salted_password” values, then attempts to SHA1
the
password in exactly the same way ruby did, and compare the values.
Presumable, matching values will mean successful password match.

Can anybody see why the output of this php code is not the same as the
login_engine code?

<?php function hashed($mystr){ return substr( sha1(LOGIN_ENGINE_CONF_SALT."--$mystr--}"), 0, 39); } function salted_password($salt, $hashed_password){ return hashed($salt . $hashed_password); } $salt = pg_fetch_result(pg_query("SELECT salt FROM users WHERE login='$u'"), 0, 0); $sqlpass = pg_fetch_result(pg_query("SELECT salted_password FROM users WHERE login='$u'"), 0, 0); $salted_password = salted_password( $salt, hashed($_POST['password']) ); if($sqlpass == $salted_password){ blah blah blah } else # oH, too bad it didn't work ?>

Top-posting to my own post from yesterday. I found the solution:

Here are the lines that matter:

Ruby

Digest::SHA1.hexdigest("#{LoginEngine.config(:salt)}–#{str}–}")[0…39]
PHP
return substr( sha1(LOGIN_ENGINE_CONF_SALT."–$mystr–}"), 0, 39);

and here’s the fix, in PHP:
return substr( sha1(LOGIN_ENGINE_CONF_SALT."–$mystr–}"), 1, 40);

Comp Sci 203. Binary representation of indices. Some index systems are
0-based and some are 1-based. Ruby’s built in [ … ] command has a
0-based
index.