15

I'm currently reading up on JWTs and have written something to create them. When I created my JWT I noticed that my signature was not being encoded properly.

For instance, given the hash

9B2317C2C941A179130D0D28961AB542C88745658BE328F557422EA0AF8F60E8

My code produces

OUIyMzE3QzJDOTQxQTE3OTEzMEQwRDI4OTYxQUI1NDJDODg3NDU2NThCRTMyOEY1NTc0MjJFQTBBRjhGNjBFOA==

What I'm expecting to get is

myMXwslBoXkTDQ0olhq1QsiHRWWL4yj1V0IuoK+PYOg=

Why are encoded hashes so different and what am I missing?

2
  • 12
    What you think is the hash is not, in fact, the hash. It is a hex-encoded string representing the hash value. You need to un-encode it to the byte-sequence that is in fact the hash before base64 encoding. Currently you're just base64 encoding the string.
    – Xander
    Dec 14, 2016 at 19:43
  • Ah, that makes sense. I also found stackoverflow.com/questions/4278170/… which helped me to understand what was going on. Dec 14, 2016 at 20:09

2 Answers 2

16

You are doing a conversion from hex encoding (or base16 if you like) to base64. So you are base64 encoding the ASCII characters 9 (57), B (66) and 2 (50) giving you OUIy.

What you should be doing is base64 encoding the raw bytes. So you should encode 0x9B (155) and 0x23 (35) giving you myM.

15

This should do;

echo 9B2317C2C941A179130D0D28961AB542C88745658BE328F557422EA0AF8F60E8 | xxd -r -p | base64

Output:

myMXwslBoXkTDQ0olhq1QsiHRWWL4yj1V0IuoK+PYOg=

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .