Python Forum

Full Version: Base64 to retrieve message
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

Trying to use Python as part of an authentication procedure for an API. What I am trying to do is to use a challenge and secret key (known values) to retreve the challenge response. I am then given the code I will need to get this value (below). The problem is that I am new to Python and can't figure out where to put my challenge and secret key-values. Can anyone help me? This is the code I have been given from the API provider to retrieve the value:

import hashlib 
import hmac 
import base64 

def base64url_encode(arg): 
    # for Python 2 
    s = base64.b64encode(arg); 
    # for Python 3 
    #s = base64.b64encode(arg).decode('utf-8'); 
    s = s.split('=')[0] 
    s = s.replace('+','-') 
    s = s.replace('/','_') 
    result = s 
    return result 

def base64url_decode(arg): 
    s = arg 
    s = s.replace('-','+') 
    s = s.replace('_','/') 
    strlen = len(s) % 4 
    if strlen == 1: s=s; 
    elif strlen == 2: s+='=='; 
    elif strlen == 3: s+='='; 
    else: raise exception('Illegal base64Url string') 
    result = base64.b64decode(s) 
    return result 

def CreateChallengeResponse(secretKey,challenge): 
    secretKeyArr = base64url_decode(secretKey) 
    challengeArr = base64url_decode(challenge) 
    hash = hmac.new(secretKeyArr, challengeArr, hashlib.sha256) 
    result = base64url_encode(hash.digest()) 
    return result 

challengeResponse = CreateChallengeResponse(secretKey,challenge)
Sorry if this is a stupid question. I would really appreciate it if someone can point me in the right direction as I am only getting error messages like TypeError: a bytes-like object is required, not 'str'.


Best regards,
Jonas