【问题标题】:Accessing the cakePHP hashed passwords from PHP service从 PHP 服务访问 cakePHP 哈希密码
【发布时间】:2013-08-20 08:53:24
【问题描述】:

我们有一些使用相同数据库的应用程序。用户密码由 cakePHP 应用程序散列。我们要做的是比较 php 服务散列的密码和 cakePHP 散列的密码。

是否有一个 PHP 函数可以模仿 CakePHP 的散列来比较密码?如果没有,最简单的方法是什么?

【问题讨论】:

    标签: php cakephp passwords cakephp-2.0


    【解决方案1】:

    我相信 CakePHP 使用 lib\Cake\Utility\Security.php 内部的函数 hash 来获取用户的哈希数据,并将其与密码字段中存储的哈希值进行比较:

    https://github.com/cakephp/cakephp/blob/master/lib/Cake/Utility/Security.php#L107

    我还要说它通常默认使用 PHP 的 sha1 函数,该函数使用用户的 passwordSecurity.salt 值(在 core.php 中定义)作为输入字符串。 因此,您可以执行以下操作来获取保存在 users 表的 password 字段中的值:

    sha1('cce93fda02c7f3ebf1g46c583589f1fd257e9d5d'. 'mypassword');
    

    这是 CakePHP 中使用 sha1 的完整函数:

    public static function hash($string, $type = null, $salt = false) {
        if (empty($type)) {
            $type = self::$hashType;
        }
        $type = strtolower($type);
    
        if ($type === 'blowfish') {
            return self::_crypt($string, $salt);
        }
        if ($salt) {
            if (!is_string($salt)) {
                $salt = Configure::read('Security.salt');
            }
            $string = $salt . $string;
        }
    
        if (!$type || $type === 'sha1') {
            if (function_exists('sha1')) {
                return sha1($string);
            }
            $type = 'sha256';
        }
    
        if ($type === 'sha256' && function_exists('mhash')) {
            return bin2hex(mhash(MHASH_SHA256, $string));
        }
    
        if (function_exists('hash')) {
            return hash($type, $string);
        }
        return md5($string);
    }
    

    您可以在CakePHP documentation 阅读更多相关信息。

    【讨论】:

    • 成功了!非常感谢。