OpenSSL与Python hashlib不匹配

时间:2014-10-18 22:59:17

标签: python openssl sha pyopenssl

我是使用OpenSSL库的新手,我无法使其输出与python的加密库的输出相匹配。以下是一个例子。

Python代码:

import hmac

secret = "asdf1234"
string = '{"request"}'

hmac.new(secret, string, hashlib.sha384).hexdigest()
    '92904f1b3c210a4fb19f476c19f24452717e85329aa9ffaba4a5fbe1111c2e3fa7f5a5fb35fdc58b3d158f5f886c3d02'

OpenSSL的:

echo -n {"request"} | openssl dgst -sha384 -hmac asdf1234 -hex

(stdin)= 4c3d525b8a7095b9063a3bd974e56f0a5872399365912297d6ee18e400d2b55d0142395ba5fb4f33655ceca209ba9570

我做错了什么?这两种实现是否正确?

1 个答案:

答案 0 :(得分:1)

要匹配openssl输出,Python字符串应为'{request}'而不是'{"request"}'

import hmac
import hashlib
secret = "asdf1234"
string = '{request}'

hmac.new(secret, string, hashlib.sha384).hexdigest()

产量

'4c3d525b8a7095b9063a3bd974e56f0a5872399365912297d6ee18e400d2b55d0142395ba5fb4f33655ceca209ba9570'

或者,如果您希望openssl命令与Python输出匹配,请使用

echo -n '{"request"}' | openssl dgst -sha384 -hmac asdf1234 -hex

产生

(stdin)= 92904f1b3c210a4fb19f476c19f24452717e85329aa9ffaba4a5fbe1111c2e3fa7f5a5fb35fdc58b3d158f5f886c3d02

毕竟,输入必须匹配输出才有机会匹配:

% echo -n {"request"}
{request}

>>> print('{"request"}')
{"request"}