Search code examples
c#androidbase64decodeencode

Base64 url safe encoding and decoding between Android and C#


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.


Solution

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