Skip to main content
 首页 » 编程设计

php之Python 中 PHP 对象的相同哈希值

2024年09月07日25dflying

我有一个小问题: 一方面,我有一个解析器,它接受一个字符串,将其包装到一个 PHP 对象中并返回该对象的散列字符串。 另一方面,一个新版本的解析器是用 Python 编写的,新的解析器接受一个字符串,对其进行哈希处理,然后也作为一个字符串返回。

我遇到了兼容性问题。 相同的字符串散列为 PHP 对象和散列为字符串返回不同的结果。有没有办法在 python 中获取 PHP 对象,以获得与 PHP 解析器中完全相同的结果? 这里有一些代码:

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); 
} 

下面是 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() 

请您参考如下方法:

确保使用相同的哈希算法。例如:

PHP

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

结果:f7fbba6e0636f890e56fbbf3283e524c6fa3204ae298382d624741d0dc6638326e282c41be5e4254d8820772c5518a2c5a8c0c7f7eda19594a7eb539453e1ed7

python

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

结果:'f7fbba6e0636f890e56fbbf3283e524c6fa3204ae298382d624741d0dc6638326e282c41be5e4254d8820772c5518a2c5a8c0c7f7eda19594a7eb539453e1ed7'