C#到PHP base64编码/解码
所以我有这个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#在编码中加了’+’但不确定。 任何线索
在发送之前,您可能应该在C#端对您的Base64字符串进行URL编码。
和URL在base64解码之前在php端解码它。
C#方面
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);
请注意, +
是base64编码中的有效字符,但在URL中使用时,它通常会被转换回空格。 这个空间可能会混淆你的PHP base64_decode
函数。
您有两种方法可以解决此问题:
- 在离开C#应用程序之前,使用%-encoding对+字符进行编码。
- 在PHP应用程序中,在传递给base64_decode之前将空格字符转换回+。
第一种选择可能是你更好的选择。
这似乎有效,用%2B取代+ …
private string HTTPPost(string URL, Dictionary FormData) { UTF8Encoding UTF8encoding = new UTF8Encoding(); string postData = ""; foreach (KeyValuePair 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; }
就我所见,Convert.ToBase64String似乎没有添加任何额外的东西。 例如:
byte[] bytes = new byte[1000]; Console.WriteLine(Convert.ToBase64String(bytes));
上面的代码在末尾打印出一堆带有==的AAAA,这是正确的。
我的猜测是,PHP端的$data
不包含C#端的内容 – 检查它们是否互相攻击。
在c#中
this is a longstring. and lets make this a3214 ad0-3214 0czcx 909340 zxci 0324#$@#$%%13244513123
变成
dGhpcyBpcyBhIDxCPmxvbmc8L2I+c3RyaW5nLiBhbmQgbGV0cyBtYWtlIHRoaXMgYTMyMTQgYWQwLTMyMTQgMGN6Y3ggOTA5MzQwIHp4Y2kgMDMyNCMkQCMkJSUxMzI0NDUxMzEyMw==
为了我。 我认为+正在打破这一切。
PHP方应该是:$ data = $ _REQUEST [‘in’]; // $ decdata = urldecode($ data); $ raw = base64_decode($ decdata);
$ _REQUEST应该已经过URL解码。