所以我有这个c#应用程序需要ping我运行linux / php堆栈的web服务器 我遇到了基本64位编码字节的c#方式的问题。
我的c#代码就像:
byte[] encbuff = System.Text.Encoding.UTF8.GetBytes("the string");
String enc = Convert.ToBase64String(encbuff);
和php方面:
$data = $_REQUEST['in'];
$raw = base64_decode($data);
大字符串100+字符失败。 我认为这是因为c#在编码中加了'+'但不确定。 任何线索
答案 0 :(得分:15)
您可能应该在发送之前对C#端的Base64字符串进行URL编码。
和URL在base64解码之前在php端解码它。
C#side
byte[] encbuff = System.Text.Encoding.UTF8.GetBytes("the string");
string enc = Convert.ToBase64String(encbuff);
string urlenc = Server.UrlEncode(enc);
和php方面:
$data = $_REQUEST['in'];
$decdata = urldecode($data);
$raw = base64_decode($decdata);
答案 1 :(得分:7)
请注意,+
是base64编码中的有效字符,但在URL中使用时,它通常会被转换回空格。这个空间可能会混淆您的PHP base64_decode
函数。
您有两种解决此问题的方法:
第一种选择可能是你更好的选择。
答案 2 :(得分:3)
这似乎有效,用%2B取代+ ......
private string HTTPPost(string URL, Dictionary<string, string> FormData)
{
UTF8Encoding UTF8encoding = new UTF8Encoding();
string postData = "";
foreach (KeyValuePair<String, String> entry in FormData)
{
postData += entry.Key + "=" + entry.Value + "&";
}
postData = postData.Remove(postData.Length - 1);
//urlencode replace (+) with (%2B) so it will not be changed to space ( )
postData = postData.Replace("+", "%2B");
byte[] data = UTF8encoding.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream strm = request.GetRequestStream();
// Send the data.
strm.Write(data, 0, data.Length);
strm.Close();
WebResponse rsp = null;
// Send the data to the webserver
rsp = request.GetResponse();
StreamReader rspStream = new StreamReader(rsp.GetResponseStream());
string response = rspStream.ReadToEnd();
return response;
}
答案 3 :(得分:1)
Convert.ToBase64String似乎没有添加任何额外的东西,据我所见。例如:
byte[] bytes = new byte[1000];
Console.WriteLine(Convert.ToBase64String(bytes));
上面的代码在末尾打印出一堆带有==的AAAA,这是正确的。
我的猜测是PHP端的$data
不包含enc
在C#端做的事情 - 互相检查。
答案 4 :(得分:0)
在c#
中this is a <B>long</b>string. and lets make this a3214 ad0-3214 0czcx 909340 zxci 0324#$@#$%%13244513123
变成
dGhpcyBpcyBhIDxCPmxvbmc8L2I+c3RyaW5nLiBhbmQgbGV0cyBtYWtlIHRoaXMgYTMyMTQgYWQwLTMyMTQgMGN6Y3ggOTA5MzQwIHp4Y2kgMDMyNCMkQCMkJSUxMzI0NDUxMzEyMw==
对我来说。我认为+正在打破这一切。
答案 5 :(得分:0)
PHP方面应该是: $ data = $ _REQUEST ['in']; // $ decdata = urldecode($ data); $ raw = base64_decode($ decdata);
$ _REQUEST应该已经过URL解码。