Android和C#之间的Base64url安全编解码

Base64 url safe encoding and decoding between Android and C#

在我的 android 应用程序中,我正在使用带有标志 URL_SAFENO_WRAPjava.util.Base64 编码和解码。

但是,当我尝试使用 HttpServerUtility.UrlTokenEncode 在我的 C# 应用程序中对其进行解码时,我返回 null。在这种情况下,我的编码字符串也无法在 Android 应用程序上解码。

我错过了什么? URL_SAFE 标志是否确保 Base64 字符串没有 +/ 和任何额外的填充?为什么 UrlTokenEncode 不接受 Base64 值?

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

UrlTokenEncode 返回 null 因为我传递的是 string 而不是 UrlToken.

在 Android 中为 encoding/decoding 坚持 URL_SAFENO_WRAP Base64 标志,我设法将我的 C# 应用程序更改为 decode/encode url_safe 态度。

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