2

Can someone explain this behavior?

Buffer.from('5d9RAjZ2GCob-86_Ql', 'base64url').toString('base64url')

// 5d9RAjZ2GCob-86_Qg

Please take a close look at the last character l - g

Ihor Sakailiuk
  • 5,642
  • 3
  • 21
  • 35
  • 2
    Base 64 encodes chunks of 3 bytes (for this reasons it has often either a protocol which decide the length, or the = at the end of a base64 string). I assume `l` and `g` will give the same bits for the last entire byte, and the rest is discarded because there is not enough information – Giacomo Catenazzi Mar 15 '22 at 13:23

1 Answers1

2

Your string is 18 characters long, With 6 bits encoded in each character it means the first 16 characters represent 96 bits (12 bytes) and the last two represent one byte plus 4 unused bits. Only the first two bits of the last character are significant here. g is 100000, l is 100101. As the last 4 characters are not used, g is just the first choice for the two bits 1 0.

So for any character in the range between g and v, you would get a g when you convert it back to Base64Url. See https://en.wikipedia.org/wiki/Base64#Base64_table_from_RFC_4648

jps
  • 20,041
  • 15
  • 75
  • 79