B4J Question JWT [SOLVED]

madru

Active Member
Licensed User
Longtime User
Hi,

can somebody teach/show me how to decode/verify a JWT token in B4x?

THX
 

madru

Active Member
Licensed User
Longtime User
OK, a little bit closer but not there .....


this is the JWT example token from the Wiki (https://en.wikipedia.org/wiki/JSON_Web_Token)

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dnZWRJbkFzIjoiYWRtaW4iLCJpYXQiOjE0MjI3Nzk2Mzh9.gzSraSYS8EXBxLN_oWnFSRgCzcmJmMjLiuyu5CSpyHI

I tried to verify the signature but the generated base64 string is different:

gzSraSYS8EXBxLN_oWnFSRgCzcmJmMjLiuyu5CSpyHI
gzSraSYS8EXBxLN/oWnFSRgCzcmJmMjLiuyu5CSpyHI=

any ideas?

THX

M

update. this does work now, I forgot about URL safe base64

B4X:
dim mykey as string = "secretkey"
dim part as string="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dnZWRJbkFzIjoiYWRtaW4iLCJpYXQiOjE0MjI3Nzk2Mzh9"
log(getHashBase64(CreateHash(mykey,"HMACSHA256",part,"ASCII")))


Sub getHashBase64(inp As String) As String


    Dim res As String =  su.EncodeBase64(bc.HexToBytes(inp))
    'URL safe, replace the chars
    res=res.Replace("+","-")
    res=res.Replace("/","_")
    If res.EndsWith("=") Then ' remove padding
        res = res.Replace("=","")
    EndIf
    Return res

EndSub

Sub CreateHash(key As String,algorithm As String,data As String,charset As String) As String

    Dim m As Mac
    Dim k AsKeyGenerator
    Dim bc AsByteConverter
    k.Initialize(algorithm)
    k.KeyFromBytes(key.GetBytes(charset))
    m.Initialise(algorithm, k.Key)
    m.Update(data.GetBytes(charset))
    Dim b() As Byte
    b = m.Sign
    Return bc.HexFromBytes(b)

EndSub
 
Last edited:
Upvote 0
Top