python中的sha512哈希值不等于php

时间:2018-06-25 09:43:10

标签: php python-3.x encryption hash

使用digest()方法的sha512哈希与PHP中使用sha512的hash_hmac不相等。

Python:

print base64.b64encode(hmac.new("key".encode("ascii"),"hello".encode("ascii"), hashlib.sha512).digest())

PHP:

<?php 
  echo base64_encode(hash_hmac('sha512', "hello", "key")); 
?>

如果我在python中使用hexdigest()方法代替digest()方法,则哈希结果是相同的。我需要使用digest()方法,因此php中是否有任何等效方法,以便我可以获得相同的哈希结果?

1 个答案:

答案 0 :(得分:0)

我猜想Python中的digest()返回的哈希值是二进制字符串,而PHP中的hash_hmac返回的是十六进制编码的字符串。因此,在PHP中,您可以执行以下操作:

echo base64_encode(hex2bin(hash_hmac('sha512', "hello", "key")));