Search code examples
pythonopensslshapyopenssl

OpenSSL does not match Python hashlib


I am new to using the OpenSSL library and I cannot get its output to match the output from python's crypto libraries. Below is an example.

Python Code:

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

What am I doing wrong? Is either implementation correct?


Solution

  • To match the openssl output, the Python string should be '{request}' rather than '{"request"}'.

    import hmac
    import hashlib
    secret = "asdf1234"
    string = '{request}'
    
    hmac.new(secret, string, hashlib.sha384).hexdigest()
    

    yields

    '4c3d525b8a7095b9063a3bd974e56f0a5872399365912297d6ee18e400d2b55d0142395ba5fb4f33655ceca209ba9570'
    

    Or, if you want the openssl command to match the Python output, use

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

    which yields

    (stdin)= 92904f1b3c210a4fb19f476c19f24452717e85329aa9ffaba4a5fbe1111c2e3fa7f5a5fb35fdc58b3d158f5f886c3d02
    

    After all, the inputs have to match for the outputs to have a chance at matching:

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

    and

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