簡體   English   中英

base64編碼和序列化數組WHMCS

[英]base64 encode and serialize array WHMCS

我使用WHMCS API。 我正在嘗試使用他們的API發出請求。該API需要將該數組進行序列化並以base64_encode進行編碼。 他們用php舉例,我嘗試將其轉換為C#代碼,但無法正常工作。

PHP代碼:

     $values["customfields"] = base64_encode(serialize(array("1"=>"Google")));

我的C#代碼:

     CustomFields[] cf = new CustomFields[2];
                    CustomFields cf0 = new CustomFields();
                    cf0.number = "16";
                    cf0.value = WebSiteTitle;
                    CustomFields cf1 = new CustomFields();
                    cf1.number = "14";
                    cf1.value = NewDomain;
                    cf[0] = cf0;
                    cf[1] = cf1;
                    byte[] bytecf = ObjectToByteArray2(cf);
                    String CString = Convert.ToBase64String(bytecf);

                    form.Add("customfields", CString);


       private static byte[] ObjectToByteArray2(Object obj)
    {
        if (obj == null)
            return null;
        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream ms = new MemoryStream();
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }


       [Serializable]
public class CustomFields
{
    public string number { get; set; }
    public string value { get; set; }
}

我做錯什么了嗎? 因為當我嘗試發出請求時,它不起作用,並且未在我要添加的位置添加此字段。

您做錯了什么:

您正在使用二進制格式化程序進行序列化...

這將生成一個字節序列,另一個二進制格式化程序將對該字節序列進行反序列化...只要您不離開.net世界(和clr版本),這就會很好,因為反序列化會很容易...這是如果您離開.net世界,那就不好了,因為通常只有 .net二進制格式化程序(具有相同的clr版本)才能理解該數據...

php的serialize()不會得到與.net的binaryformatter相同的結果,因此反序列化將失敗

這里的另一個問題是,它沒有指定如何將php的serialize()的輸出字符串編碼為字節...有很多方法可以實現,每種方法都會產生另一系列的字節...您需要首先了解編碼...可能是ascii,但這只是一個猜測...

要在c#中實現您自己的serialize()版本,您的函數必須返回以下內容,給定類似php示例的輸入:

一個:1:{S:1: “1”; S:6: “谷歌”}

一個:尺寸:{密鑰;值;重復]}

而字符串必須表示為:

S:長度: “the_string_itself”

因此,假設WebSiteTitle和NewDomain是垃圾字符串,那么您的示例在serialize()之后應如下所示

一:2:{S:2: “16”; S:12: “WebSiteTitle”; S:2: “14”; S:9: “NEWDOMAIN”}

從那里,您將需要使用該API期望的任何編碼方式將其編碼為字節,然后將該字節流編碼為base64字符串

.Net中的BinaryFormatter高度依賴於平台,因此不能在編程語言之間的各種CLR版本中使用。 當在數組上調用PHP序列化函數時,實際上將產生應足夠簡單的輸出以在C#中進行復制,例如:

$array["a"] = "Foo";
$array["b"] = "Bar";
print serialize($array);

結果:

a:2:{s:1:"a";s:3:"Foo";s:1:"b";s:3:"Bar";}

嘗試

 public static string phpStringArray(Dictionary<string, string> arr)
 {
     StringBuilder sb = new StringBuilder("a:")
         .Append(arr.Count).Append(":{");

     foreach (string key in arr.Keys)
     {
         sb.AppendFormat("s:{0}:\"{1}\";s:{2}:\"{3}\";",
             key.Length, key, arr[key].Length, arr[key]);
     }

     return sb.Append('}').ToString();
 }

然后

Console.WriteLine(
         phpStringArray(
             new Dictionary<string, string> { { "a", "Foo" }, { "b", "Bar" } })
         );

只需要對Base64進行編碼即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM