[英]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
.在我的 android 应用程序中,我使用带有标志
URL_SAFE
和NO_WRAP
java.util.Base64
编码和解码。
However, when I try to decode it in my C# application using HttpServerUtility.UrlTokenEncode
, I am getting back null
.但是,当我尝试在我的 C# 应用程序中使用
HttpServerUtility.UrlTokenEncode
对其进行解码时,我返回null
。 At this state, my encoded string cannot also be decoded on the Android application.在这种状态下,我的编码字符串也无法在 Android 应用程序上解码。
What am I missing out on?我错过了什么? Doesn't the
URL_SAFE
flag ensure that the Base64 string has no +
, /
and any extra padding? URL_SAFE
标志是否确保 Base64 字符串没有+
、 /
和任何额外的填充? How come UrlTokenEncode
is not accepting the Base64 value? UrlTokenEncode
不接受 Base64 值?
I was using this post as reference, for anyone who is interested. 我正在使用这篇文章作为参考,供任何有兴趣的人使用。
UrlTokenEncode
returned null
because I was passing a string
and not a UrlToken
. UrlTokenEncode
返回null
因为我传递的是string
而不是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.坚持使用
URL_SAFE
和NO_WRAP
Base64 标志在 Android 中进行编码/解码,我设法将我的 C# 应用程序更改为以 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.