14

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?

Anders
  • 64,406
  • 24
  • 178
  • 215
etchesketch
  • 243
  • 1
  • 2
  • 5
  • 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 '16 at 19:43
  • Ah, that makes sense. I also found http://stackoverflow.com/questions/4278170/md5-hash-and-base64-encoding which helped me to understand what was going on. – etchesketch Dec 14 '16 at 20:09

2 Answers2

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.

Anders
  • 64,406
  • 24
  • 178
  • 215
12

This should do;

echo 9B2317C2C941A179130D0D28961AB542C88745658BE328F557422EA0AF8F60E8 | xxd -r -p | base64

Output:

myMXwslBoXkTDQ0olhq1QsiHRWWL4yj1V0IuoK+PYOg=
Anders
  • 64,406
  • 24
  • 178
  • 215
Akash Mehta
  • 221
  • 2
  • 2