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_str 和 registration_window 是字符串。在 Python 中,格式化字符串的一种方法是使用 % 运算符。例如,
def sayGreeting(name):
return "Hello %s" % name
此字符串运算符与您要使用的运算符不同,后者是计算两个整数余数的模数运算符。
PHP 中的strtotime 函数返回一个整数,它是日期和时间的字符串表示形式的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 用于任何关注安全性的应用程序。它不是安全的散列函数。
