Stasello Boldirev
Stasello Boldirev

Reputation: 133

Same hash of PHP object in Python

I have a little problem: On one hand I have a parser, which takes a string, wraps it into a PHP object and returns a hashed string of this object. On the other hand a new version of parser is written on Python and new parser take a string, hash it and return also as a string.

And there I have a compability issue. The same string hashed as PHP object and hashed as string returns a different result. Is there a way to get PHP object in python, to obtain exact same result as in PHP-parser? Here a bites of code:

PHP:

function num_converter() {
    $string_1 = '1234';
    $string_2 = '567890';

    $hash = String_to_hash::stringHash((object)array(
                        'number'=>$string_1.' '.$string_2,
                        'number2'=>$number3,
                ));
    return array_push($Reply, $hash);
}

And here is same functionality code in Python:

def num_converter():
    string_1 = '1234'
    string_2 = '567890'
    number3 = digits # type of int

    string_to_hash = string_1 + " " + string_2 + str(number3)
    return hashlib.md5(string_to_hash.encode()).hexdigest().upper()

Upvotes: 2

Views: 1223

Answers (1)

Tobias Lorenz
Tobias Lorenz

Reputation: 1448

Make sure to use the same hash algorithm. For example:

PHP

php > echo hash('sha512', 'foo');

Result: f7fbba6e0636f890e56fbbf3283e524c6fa3204ae298382d624741d0dc6638326e282c41be5e4254d8820772c5518a2c5a8c0c7f7eda19594a7eb539453e1ed7

Python

import hashlib
hashlib.sha512(b'foo').hexdigest()

Result: 'f7fbba6e0636f890e56fbbf3283e524c6fa3204ae298382d624741d0dc6638326e282c41be5e4254d8820772c5518a2c5a8c0c7f7eda19594a7eb539453e1ed7'

Upvotes: 3

Related Questions