I want to achieve Base64 URL safe encoding in C#. In Java, we have the common Codec
library which gives me an URL safe encoded string. How can I achieve the same using C#?
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes("StringToEncode");
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
The above code converts it to Base64, but it pads ==
. Is there is way to achieve URL safe encoding?
It is common to simply swap alphabet for use in urls, so that no %-encoding is necessary; only 3 of the 65 characters are problematic - +
, /
and =
. the most common replacements are -
in place of +
and _
in place of /
. As for the padding: just remove it (the =
); you can infer the amount of padding needed. At the other end: just reverse the process:
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes)
.TrimEnd(padding).Replace('+', '-').Replace('/', '_');
with:
static readonly char[] padding = { '=' };
and to reverse:
string incoming = returnValue
.Replace('_', '/').Replace('-', '+');
switch(returnValue.Length % 4) {
case 2: incoming += "=="; break;
case 3: incoming += "="; break;
}
byte[] bytes = Convert.FromBase64String(incoming);
string originalText = Encoding.ASCII.GetString(bytes);
The interesting question, however, is: is this the same approach that the "common codec library" uses? It would certainly be a reasonable first thing to test - this is a pretty common approach.