A
A
Alexander2018-06-11 21:52:22
PHP
Alexander, 2018-06-11 21:52:22

Why don't HMAC SHA256 results match for PHP and PYTHON?

It is necessary to redo the script in PYTHON, but the HASHES do not match. Help understand why
PHP

function createHash($data)
{
    $privateKey = 'Xahtc9ktbs5-t900NF04Kx2-xTFCByr2vBj-ZOtjgFLm7Um-8H08LLGOizt-U9ssAvXbOWZ-gefVZB2TXbA';

    $_data = array(
        'modelName' => isset($data['modelName']) ? $data['modelName'] : null,
        'calledMethod' => isset($data['calledMethod']) ? $data['calledMethod'] : null,
        'methodProperties' => isset($data['methodProperties']) ? $data['methodProperties'] : null,
    );

    return hash_hmac('sha256', http_build_query($_data), $privateKey);
}

$data = array();

        $data["modelName"] = "Mizol_Product";
        $data["calledMethod"] = "getProducts";
        $data["apiKey"] = 52542;
        $data['hash'] = createHash($data);

        echo '<pre>';
        print_r($data);
        echo '</pre>';

PYTHON
def create_hash(data):
    private_key = 'Xahtc9ktbs5-t900NF04Kx2-xTFCByr2vBj-ZOtjgFLm7Um-8H08LLGOizt-U9ssAvXbOWZ-gefVZB2TXbA'
    _data = {
        'modelName': data['modelName'] if data.get('modelName') else None,
        'calledMethod': data['calledMethod'] if data.get('calledMethod') else None,
        'methodProperties': data['methodProperties'] if data.get('methodProperties') else None,
    }
    return hmac.new(
        private_key.encode(),
        urllib.parse.urlencode(_data).encode(),
        hashlib.sha256
    ).hexdigest()


def make_request_data(model_name='Mizol_Product', called_method='getProducts', api_key=52542):
    data = {
        'modelName': model_name,
        'calledMethod': called_method,
        'apiKey': api_key,
    }
    data['hash'] = create_hash(data)
    print(data)
    return data

Result in PHP
Array
(
    [modelName] => Mizol_Product
    [calledMethod] => getProducts
    [apiKey] => 52542
    [hash] => 40a14879fd40f48c0a3618594f3d93b93a76423f62a0d3a305032d07bc8f2d5d
)

Result in PYTHON
{
    'modelName': 'Mizol_Product',
    'calledMethod': 'getProducts',
    'apiKey': 52542,
    'hash': '54f4538d59a11e936acbe2f23b100633d3961ef5a269855fbe6e399e8b28e82c'
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
spaceatmoon, 2018-06-11
@vintkor

Print it out
and
you will immediately see the difference. And the rule of good form is to add imports to the code.

R
Roman Kitaev, 2018-06-11
@deliro

Because the order in the associative array is different.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question