How to achieve Base64 URL safe encoding in C#? -
How to achieve Base64 URL safe encoding in C#? -
i want accomplish base64 url safe encoding in c#. in java, have mutual codec
library gives me url safe encoded string. how can accomplish same using c#?
byte[] toencodeasbytes = system.text.asciiencoding.ascii.getbytes("stringtoencode"); string returnvalue = system.convert.tobase64string(toencodeasbytes);
the above code converts base64, pads ==
. there way accomplish url safe encoding?
it mutual simply swap alphabet utilize in urls, no %-encoding necessary; 3 of 65 characters problematic - +
, /
, =
. mutual replacements -
in place of +
, _
in place of /
. padding: just remove it (the =
); can infer amount of padding needed. @ other end: reverse process:
string returnvalue = system.convert.tobase64string(toencodeasbytes) .trimend(padding).replace('+', '-').replace('/', '_');
with:
static readonly char[] padding = { '=' };
and 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 same approach "common codec library" uses? reasonable first thing test - pretty mutual approach.
c# encoding base64
Comments
Post a Comment