How to Achieve Base64 Url Safe Encoding in C#

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;
}

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 do I encode and decode a base64 string?


Encode

public static string Base64Encode(string plainText) {
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}

Decode

public static string Base64Decode(string base64EncodedData) {
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}

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 :(

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)

Using statement for Base64UrlEncode

"Base64UrlEncode" is just a custom function:

private static string Base64UrlEncode(string input) {
var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
// Special "url-safe" base64 encode.
return Convert.ToBase64String(inputBytes)
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
}

How do I convert the following remote URL to a base64 safe URL with C#?

In case you need to encode both URL and Image (may not be what you need, but might be useful sometime)

string url = "https://scontent.xx.fbcdn.net/v/t1.0-9/15665479_1260320054027269_4201232212927955955_n.jpg?oh=ee01f2ec47b2e972bc12f99d988db241&oe=5946A159";

string encodedUrl = Convert.ToBase64String(Encoding.Default.GetBytes(url));

using (var client = new WebClient())
{
byte[] dataBytes = client.DownloadData(new Uri(url));
string encodedFileAsBase64 = Convert.ToBase64String(dataBytes);
}


Related Topics



Leave a reply



Submit