Python Forum

Full Version: digest header generating issue
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
I'm trying to generate digest header for the request similarly to JavaScript code from example, however python script produces different result

This is JavaScript code:

import sha256 from "crypto-js/sha256";
import Base64 from "crypto-js/enc-base64";

// Test payload to compare python and js output
const payload = {
    code: "this_is_fake_code",
    grant_type: "authorization_code",
    redirect_uri: "this_is_redirect_url",
};

function calculateDigest() {
    const payload_data = JSON.stringify(payload);
    const sha256digest = sha256(payload_data);
    const base64sha256 = Base64.stringify(sha256digest);
    const calculatedDigest = "sha-256=" + base64sha256;
    return calculatedDigest;
}

calculateDigest();
Origin of JavaScript code Nordea API ; function name in doc is also calculateDigest
It produces digest: sha-256=wAbReUicUDARTKnA4WTiEcJulJ65E06wKrxf6ijiVtw=

And this is Python code:
import hashlib
import base64
import json
import collections
from urllib.parse import urlencode
from hashlib import blake2b

# Test payload to compare python and js output
payload = {
    'code': 'this_is_fake_code',
    'grant_type': "authorization_code",
    'redirect_uri': 'this_is_redirect_url'
}

digest_str = json.dumps(payload).encode('utf-8')
sha256digest = hashlib.sha256(digest_str).hexdigest()

base64sha256 = base64.b64encode(bytes(sha256digest, 'utf-8')).decode()
# base64sha256 = base64.b64encode(sha256digest).decode()
digest = 'sha-256=' + base64sha256
It produces digest: sha-256=ODhjM2NkMWZjN2I0YTM4M2Q0YzYyZjVmNGIzZjZhMDY1Y2YwZmIzMGJmY2E0NzkwYzk0NjEyMGRkYmUwNjQ0Yw==

Can you help me to create a code that will produce result equal to crypto-js library but in python?
# simple and reliable
@auth.post("/login")
def auth_login():
    email = request.forms.get("mail")
    pswd = request.forms.get("password")

    if auth_mail(email) is False:
        cur = con.cursor()
        sql = "SELECT id, name, mail, password FROM user_table WHERE mail=?"
        res = cur.execute(sql, (email,))
        row = res.fetchone()
        row.keys()
        cur.close()
        if bcrypt.checkpw(pswd.encode(), row["password"]):
            payload = {
                "id": row["id"],
                "name": row["name"],
                "mail": row["mail"],
            }

            visited = jwt.encode(payload, key, algorithm)
            response.set_cookie(
                "visited",
                visited,
                path="/",
                httponly=True,
            )
            return redirect("/")
        return HTTPError(
            401, "Sorry.. The password doesn't match..!"
        )
    return HTTPError(401, "Sorry.. NO user..!")