Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Base64 to retrieve message
#1
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  download base64 email attachment cferguson 3 4,647 Feb-25-2020, 06:50 PM
Last Post: cferguson
  decode base64 with python give error thailq 3 3,829 Sep-24-2018, 12:39 AM
Last Post: thailq
  Unable to read data from string base64 representing a .xlsx file max 2 15,187 Apr-05-2018, 07:58 PM
Last Post: max
  base64 decoding issue or bug rbrahmaa 2 13,958 Apr-25-2017, 11:56 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020