Home > Software engineering >  PHP bcrypt to PYTHON bycrypt not giving same values
PHP bcrypt to PYTHON bycrypt not giving same values

Time:01-21

Hello I am building an API on python to create a user and insert password in database. The problem is that the application is on Laravel PHP and using bcrypt.
For example encrypting "test1234$%" in PYTHON gives "$2b$12$rsGZPtjctbI6bSGzS4P3mOSdrABnJuHfnKxEQwvm4KFu72BN3XNKK" and encrypting same in PHP gives "$2y$10$cO2nvRURLRdlW8j6CbWu8OeVlv7dyeozpBZcxVB2nd8hbyILyg7Xa"

and when trying to login with users created by the api on the app it does not work. Even if i test with this it does not work the output is invalid:

$hash = '$2b$12$rsGZPtjctbI6bSGzS4P3mOSdrABnJuHfnKxEQwvm4KFu72BN3XNKK';

//validade hash in php
if(password_verify ( "test1234$%", $hash )){
  echo "valid";
} else {
  echo "invalid";
}

echo("\n".phpversion());

on python side used the following code:

pip install bcrypt

 import bcrypt
 
 password = item.password
 bpassword = b"password"
 hashed = bcrypt.hashpw(bpassword, bcrypt.gensalt())

on PHP side:

if (! function_exists('bcrypt')) {
    /**
     * Hash the given value against the bcrypt algorithm.
     *
     * @param  string  $value
     * @param  array  $options
     * @return string
     */
    function bcrypt($value, $options = [])
    {
        return app('hash')->driver('bcrypt')->make($value, $options);
    }
}

CodePudding user response:

bcrypt use different salt each runtime that is why its perfect for storing password on database... unless you force it to use the same salt each time it will keep generating different resulting hash

CodePudding user response:

I found a solution in the Python api i call bcrypt in PHP using subprocess

code = """echo password_hash("""'"' item.password '"'""",PASSWORD_BCRYPT);"""
    hashed_password = await myClass.php(code)
  async def php(self, code):
        p = subprocess.Popen(["php", "-r", code],
                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out = p.communicate()
        if out[1] != b'': raise Exception(out[1].decode('UTF-8'))
        return out[0].decode('UTF-8')
  •  Tags:  
  • Related