1

In my android application, I am using java.util.Base64 encoding and decoding with the flags URL_SAFE and NO_WRAP.

However, when I try to decode it in my C# application using HttpServerUtility.UrlTokenEncode, I am getting back null. At this state, my encoded string cannot also be decoded on the Android application.

What am I missing out on? Doesn't the URL_SAFE flag ensure that the Base64 string has no +, / and any extra padding? How come UrlTokenEncode is not accepting the Base64 value?

I was using this post as reference, for anyone who is interested.

Community
  • 1
  • 1
BurninatorDor
  • 1,009
  • 5
  • 19
  • 42

1 Answers1

1

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;
    }
BurninatorDor
  • 1,009
  • 5
  • 19
  • 42
  • Useful thanks. But isn't there a C# version of url_safe encoding that does not require us to manually replace all these values (=, +, /) ? – Spyder Jul 31 '18 at 13:11
  • 1
    Pay attention, replace 'str.Replace('-', '+')' and 'str.Replace('_', '/')' with 'str = str.Replace('-', '+')' and 'str = str.Replace('_', '/')'. – stfno.me Jul 30 '19 at 09:41