Forum: Rails Engines salted_password() in php

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Chris Fortune (Guest)
on 2006-06-13 00:54
(Received via mailing list)
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
?>
Chris Fortune (Guest)
on 2006-06-13 19:07
(Received via mailing list)
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.
This topic is locked and can not be replied to.