I was trying to build oauth for an application. When I get the authorization code from the authentication server, I need to verify the authorization code by comparing with the c_hash value from id_token. But, how to calculate the c_hash of the authorization code?.
Till now, I have followed the following steps but not working:
For Example:
Header of id_token:
{
"kid": "1",
"alg": "ES256"
}
Payload of id_token:
{
"sub": "mahbubcseju",
"aud": [
"19968562382010"
],
"c_hash": "xd7NpSKb8Tvs1Q2-6t-ygQ",
"iss": "https://authserver.mahbubcseju.com",
"exp": 1608974358,
"iat": 1608887958,
"nonce": "dfa2c8164652312d6736bdc0b0b037b7"
}
Authorization code:'DXGp71nPXpv32QrasRjIZDFukiVVE7gk558mBtGqjjQ'
Code
import hashlib
import base64
hash = hashlib.sha256('DXGp71nPXpv32QrasRjIZDFukiVVE7gk558mBtGqjjQ').hexdigest()
l = len(hash)
left_half = hash[:l//2]
base64_encoded = str(base64.b64encode(left_half.encode()))
Output: YzVkZWNkYTUyMjliZjEzYmVjZDUwZGJlZWFkZmIyODE=
But c_hash value and output are supposed to be equal but they are not. What can I do ? Any suggestion
You should use the raw bytes and not the hex representation.
import base64
import hashlib
hash = hashlib.sha256('DXGp71nPXpv32QrasRjIZDFukiVVE7gk558mBtGqjjQ'.encode()).digest()
left_half = hash[:len(hash)//2]
base64_encoded = str(base64.b64encode(left_half))
>>> base64_encoded
b'xd7NpSKb8Tvs1Q2+6t+ygQ=='