29

What is the range of possible characters returned from this string?

function base64url_encode($data) 
{ 
  return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); 
} 

My guess is [a-z0-9-_]

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
Chris Muench
  • 17,444
  • 70
  • 209
  • 362

2 Answers2

48

Base64 encoded strings may contain the characters a-z A-Z 0-9 + / =.

You're removing the right-padding = and replacing + with - and / with _.

So in your case, the possible characters are a-z A-Z 0-9 - _

More Info

huysentruitw
  • 27,376
  • 9
  • 90
  • 133
Floern
  • 33,559
  • 24
  • 104
  • 119
45

The range of possible characters returned are:

  • A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z
  • a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z
  • 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
  • - (minus) and _ (underscore)

In your regex-style, that would be [a-zA-Z0-9_-].

salathe
  • 51,324
  • 12
  • 104
  • 132
  • 13
    sorry to revive an old post.. but it's worth mentioning that `base64encode` likes to add `=` to the end of some string as "padding" to keep string length a modulo 4 number. See answer: http://stackoverflow.com/a/4492448/648350 – haxxxton Aug 20 '14 at 06:50
  • 5
    @haxxxton and those `=` are being explicitly `rtrim`-ed in the question's `base64url_encode` function. – salathe Aug 20 '14 at 15:49
  • 5
    @salathe agreed, i just thought it was worth mentioning what the default behaviour for `base64encode` was, as when i was searching for what it's possible values were, this was one of the first posts that came up :) – haxxxton Aug 20 '14 at 23:55
  • 8
    there is also an '=' equal sign just like this string "RElMR19OZXdzX0NlbnRyYWxfMjAxMTExMThfZGE2NTU0NjI0Zi5qcGc=.jpg" – Frederick G. Sandalo Jan 05 '15 at 10:10
  • 2
    @FrederickG.Sandalo check the original question, the equals sign (=) is getting (r)trimmed. – salathe Jan 05 '15 at 13:44
  • 1
    ahhh yeah, I didnt notice the rtrim() function there – Frederick G. Sandalo Jan 05 '15 at 17:11