简体   繁体   English

相当于 PHP 中 hash_hmac 的 Python

[英]Python equivalent of hash_hmac in PHP

I would like to convert the following php code to python我想将以下 php 代码转换为 python

"<?php echo(strtoupper(hash_hmac('SHA256', $hashinput, pack('H*',$securesecret)))); ?>"

and this is what l came up with这就是我想出的

base64.b64encode(hmac.new(bytearray(securesecret.upper(), "ASCII") bytearray(hashInput.rstrip('&'),"ASCII") , hashlib.sha512).digest())).decode("ASCII").replace("\n", "").upper())

But it is not working?但它不起作用?

You had many syntax error in your code (forgotten commas, parenthesis incoherence, etc.).您的代码中有许多语法错误(忘记逗号、括号不连贯等)。 Split the code into lines, so you can develop it correctly:将代码拆分成行,以便您可以正确开发它:

my_secure = bytearray(securesecret.upper(), "ASCII")
my_input = bytearray(hashInput.rstrip('&'),"ASCII")
my_hmac = hmac.new(my_secure, my_input, hashlib.sha512)
my_hmac_digest = my_hmac.digest()

base64.b64encode(my_hmac_digest).decode("ASCII").upper()

Then you can merge it into 1 line:然后您可以将其合并为 1 行:

base64.b64encode(hmac.new(bytearray(securesecret.upper(), "ASCII"), bytearray(hashInput.rstrip('&'),"ASCII"), hashlib.sha512).digest()).decode("ASCII").upper()

Note: using replace("\\n", "") to remove new lines is useless, base64.b64encode will not split output into lines ( base64.encodestring will)注意:使用replace("\\n", "")删除新行是没有用的, base64.b64encode不会将输出拆分成行( base64.encodestring会)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM