Code for Decoding/Encoding a Modified Base64 Url (In ASP.NET Framework)

Code for decoding/encoding a modified base64 URL (in ASP.NET Framework)

This ought to pad it out correctly:-

 base64 = base64.PadRight(base64.Length + (4 - base64.Length % 4) % 4, '=');

How to achieve Base64 URL safe encoding in C#?

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.

Base64 url safe encoding and decoding between Android and C#

UrlTokenEncode returned null because I was passing a string and not a UrlToken.

Sticking to the URL_SAFE and NO_WRAP Base64 flags for both encoding/decoding in Android, I managed to change my C# application to decode/encode in a url_safe manner.

    public string UrlEncode(string str)
{
if (str == null || str == "")
{
return null;
}

byte[] bytesToEncode = System.Text.UTF8Encoding.UTF8.GetBytes(str);
String returnVal = System.Convert.ToBase64String(bytesToEncode);

return returnVal.TrimEnd('=').Replace('+', '-').Replace('/', '_');
}

public string UrlDecode(string str)
{
if (str == null || str == "")
{
return null;
}

str.Replace('-', '+');
str.Replace('_', '/');

int paddings = str.Length % 4;
if (paddings > 0)
{
str += new string('=', 4 - paddings);
}

byte[] encodedDataAsBytes = System.Convert.FromBase64String(str);
string returnVal = System.Text.UTF8Encoding.UTF8.GetString(encodedDataAsBytes);
return returnVal;
}

Encoding to base64

The problem is that the result of decoding your input isn't 106741348187B6727213596553EA3BE8A9C3; it's \01067\041348187B6727213596553EA3BE8A9C3. Note the two null bytes, which are presumably getting stripped before you re-encode it.

If you decode and re-encode without stripping those nulls, you get the input back:

$ echo "ADEwNjcANDEzNDgxODdCNjcyNzIxMzU5NjU1M0VBM0JFOEE5QzM=" | base64 -d | base64
ADEwNjcANDEzNDgxODdCNjcyNzIxMzU5NjU1M0VBM0JFOEE5QzM=

To better see what's going on, look at the actual bytes being output by your decoder:

$ echo "ADEwNjcANDEzNDgxODdCNjcyNzIxMzU5NjU1M0VBM0JFOEE5QzM=" | base64 -d | od -c
0000000 \0 1 0 6 7 \0 4 1 3 4 8 1 8 7 B 6
0000020 7 2 7 2 1 3 5 9 6 5 5 3 E A 3 B
0000040 E 8 A 9 C 3
0000046

How to BASE64 encode URLs?

In C#:

static public string EncodeTo64(string toEncode) {
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
static public string DecodeFrom64(string encodedData) {
byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
string returnValue = System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
return returnValue;
}
MessageBox.Show(DecodeFrom64("aHR0cDovL3d3dy5pbWRiLmNvbS90aXRsZS90dDA0MDE3Mjk="));

Use System.Text.UTF8Encoding.UTF8.GetBytes(...) if string toEncode contains characters outside of ASCII. Note that in this case any party that decodes the URL will have to be able to correctly handle these characters.

Also look at the case of =, + and / mentioned by David Hardin to see if any of the problems mentioned apply to you. Or just use David's answer.

jQuery: google 'jquery base64 encode' (the site plugins.jquery.com seems to be offline at the moment, so I cannot check it for sure)

C#: base64url according to RFC4648

Based on the comments, it sounds like System.Web.HttpServerUtility.UrlTokenEncode does the right thing except for the extra character for padding. So you should be able to do:

string customBase64 = HttpServerUtility.UrlTokenEncode(data);
string rfc4648 = customBase64.Substring(0, customBase64.Length - 1);

However, you should add unit tests to check that it really does use the RFC 4648 alphabet (and in the same way as RFC 4648). It's somewhat surprising that the docs are so sparse :(

Django rest framework returning base64 image URL encoded

I managed to solve this issue by creating a dict for the base64 images outside the serializer of the model, which was the one doing that URL encoding. I also had to remove new line characters as the response was drawing them as characters.

with open(f"image_file.jpg" , "rb") as image_file:
images_dict["image_1"] = base64.encodebytes(image_file.read()).decode('utf-8').replace("\n", "")


Related Topics



Leave a reply



Submit