根据 PHP 代码在 Python 中创建 MD5 哈希

Create MD5 hash in Python based on PHP code

PHP 中的代码我需要移动到 python

[md5 key] = md5( ( [Request Timestamp] % [Registration Window] ) . [salt] );

示例:

<?php
function get_md5_hash($strDatetime, $strAuthWindow, $strSalt) {
return md5((strtotime($strDatetime) % ((int)$strAuthWindow)) .$strSalt);
}
print get_md5_hash("2013-04-29T20:51:29GMT+0300", "604800", "155961");
?>

Python 代码到此为止

timestamp = datetime.datetime.now() - timedelta(hours=6)
timestamp_str = '{:%Y-%m-%dT%H:%M:%S}'.format(timestamp)

salt = "454243"
registration_window = "604800"

import hashlib

md5_key = hashlib.md5(((timestamp_str % registration_window) .salt).encode('utf-8')).hexdigest()

我无法克服此错误消息:

TypeError: not all arguments converted during string formatting

您面临的问题基本上归结为 timestamp_strregistration_window 是字符串。在 Python 中,格式化字符串的一种方法是使用 % 运算符。例如,

def sayGreeting(name):
    return "Hello %s" % name

此字符串运算符与您要使用的运算符不同,后者是计算两个整数余数的取模运算符。

PHP中的strtotime函数returns一个整数,它是一个日期和时间的字符串表示的Unix时间戳。要在 Python 中获得相同的结果,您还需要将时间戳转换为 Unix 时间戳整数。

PHP 中的字符串连接是使用 . 运算符完成的。但是,在 Python 中,这是 + 运算符。这就是为什么您需要将 .salt 更改为 + salt 的原因,因为您正在将 salt 连接到 Unix 时间戳。

我写了一些代码来帮助您入门。

import datetime
import time
import hashlib

timestamp = datetime.datetime.now() - datetime.timedelta(hours=6)
unix_time = time.mktime(timestamp.timetuple())

salt = "454243"
registration_window = 604800

resulting_timestamp = str(unix_time % registration_window)

md5_digest = hashlib.md5(resulting_timestamp + salt).hexdigest()

切记切勿将 MD5 用于任何关注安全性的应用程序。它不是安全哈希函数。

使用这个

md5_digest = hashlib.md5((resulting_timestamp + salt).encode('utf-8')).hexdigest()

因此,在尝试找到解决方案又过了大约 2 周之后,我仍然没有可以生成所需 md5 哈希的工作 python 代码。但是,我确实有一个 "hack" 解决方案确实有效,所以我会 post 已经在这里更新,以防我找到 python 解决方案。

我所做的是 运行 PHP 中的论坛并将解决方案导入到我的 python 代码中。

utils.py

import subprocess

proc = subprocess.Popen("php md5.php", shell=True, stdout=subprocess.PIPE)
script_response = proc.stdout.read()

script_response1 = script_response.decode().split('|')[0]

md5.php

<?php

$strAuthWindow = 604800;
$strSalt = "454243";

function get_md5_hash($strDatetime, $strAuthWindow, $strSalt) {
return md5((strtotime($strDatetime) % ((int)$strAuthWindow))
.$strSalt);
}

print("$strDatetime");
print get_md5_hash("$strDatetime,", "$strAuthWindow", "$strSalt");

?>