gpt4 book ai didi

python - 基于PHP代码在Python中创建MD5哈希

转载 作者:太空宇宙 更新时间:2023-11-04 07:55:30 25 4
gpt4 key购买 nike

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 函数返回一个整数,它是日期和时间的字符串表示形式的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 用于任何关注安全性的应用程序。它不是安全的散列函数。

关于python - 基于PHP代码在Python中创建MD5哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49519804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com