C#到PHP base64的编码/解码

本文关键字:编码 解码 base64 PHP | 更新日期: 2023-09-27 17:47:48

所以我有一个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#到PHP base64的编码/解码

在发送Base64字符串之前,您可能应该在C#端对其进行URL编码。

在base64解码之前,在php端对其进行URL解码。

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

Convert.ToBase64String似乎没有添加任何额外的内容。例如:

byte[] bytes = new byte[1000];
Console.WriteLine(Convert.ToBase64String(bytes));

上面的代码打印出一堆AAAA,末尾有==,这是正确的。

我的猜测是,PHP端的$data不包含enc在C#端所做的内容——请相互检查。

在c#中

this is a <B>long</b>string. and lets make this a3214 ad0-3214 0czcx 909340 zxci 0324#$@#$%%13244513123

变成

dGhpcyBpcyBhIDxCPmxvbmc8L2I+c3RyaW5nLiBhbmQgbGV0cyBtYWtlIHRoaXMgYTMyMTQgYWQwLTMyMTQgMGN6Y3ggOTA5MzQwIHp4Y2kgMDMyNCMkQCMkJSUxMzI0NDUxMzEyMw==

对我来说。我认为+正在打破一切。

PHP端应该是:$data=$_REQUEST['in'];//$decdata=url解码($data);$raw=base64_decode($decdata);

$_REQUEST应该已经被URLdecoded。