Puneet Pant
Puneet Pant

Reputation: 1048

How to decode signature part of JSON Web Token

I am having the following JSON Web Token:-

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiI0NXo2bHdCVm9oVUVHU1p5RjdaREpIOFdZQTZ2blJWciIsImlhdCI6IjE1NjMyNjI0NTkuNjMiLCJhdWQiOiJwd2Etc2VhcmNoIiwiZXhwIjoxNTYzMjYzMzU5LCJzdWIiOiI4YmYxMzFmYi0zODJhLTRhODgtOWMxZS05NDk0Y2Q3ODdlYmYifQ.xlQ7tk_LADnw2whWVafyKCBc9cPKIRSSQo2kVxbynCA

Now if I base64 decode it I get:-

{"alg":"HS256","typ":"JWT"}
{"iss":"45z6lwBVohUEGSZyF7ZDJH8WYA6vnRVr","iat":"1563262459.63","aud":"pwa-search","exp":1563263359,"sub":"8bf131fb-382a-4a88-9c1e-9494cd787ebf"}
�T;�O��9��VU��( \���!�B��W�

The last part of it i.e. signature did not get decoded. It shows some strange characters (�T;�O��9��VU��( \���!�B��W�). I want to decode it as well so that I can know the exact value of it.

How can I decode it ?

Upvotes: 2

Views: 4410

Answers (1)

jps
jps

Reputation: 22555

The signature is indeed base64url encoded and you can decode it. But the result is a numerical value which is not meant to be printed. You can decode with a base64url library and view the value in your program. The result is a byte array which represents the hash value calculated with header, payload and secret as an input.

As it is a C# question and you asked how to decode it, here's a code snippet that does the conversion manually without any extra libs:

string signatureBase64UrlEncoded = "xlQ7tk_LADnw2whWVafyKCBc9cPKIRSSQo2kVxbynCA";

string signatureBase64Encoded = signatureBase64UrlEncoded
            .Replace('_', '/').Replace('-', '+');
switch (signatureBase64Encoded.Length % 4)
{
    case 2: signatureBase64Encoded += "=="; break;
    case 3: signatureBase64Encoded += "="; break;
}

var decodedSignature = System.Convert.FromBase64String(signatureBase64Encoded);

The code to convert the signature from base64url to base64 encoding is taken from Mark Gravell's answer here

The decodedSignature is a byte array:

enter image description here

Maybe this answer is interesting for you, as it explains how to create the signature and convert the values to base64url encoding.

Upvotes: 4

Related Questions