2017-05-31 103 views
1

我有問題序列化JSON文本到包含SecureString變量的對象。我如何序列化以下內容,同時保持public pwd變量爲SecureString?JSON ToObject與SecureString

比方說,有以下字符串:

string j_str = "{ 'uid':'JohnDoe', 'age':30, 'pwd':'MyPassword' }"; 

,我想這個字符串序列化爲一個對象我在C#

public class User 
{ 
    public string uid = { get; set; } 
    public string age = { get; set; } 
    public SecureString pwd = { get; set; } 
} 

所以我可能使用JSON ToObject以下調用)用Newtonsoft調用如下:

JObject j_obj = JObject.Parse(j_str); 

User newUser = j_obj.ToObject<User>(); 

這會導致以下錯誤:

Newtonsoft.Json.JsonSerializationException: 'Error converting value "MyPassword" to type 'System.Security.SecureString'. Path 'pwd' 
+0

變化pwd'屬性''到的類型string' –

+1

_ 「同時又保持了大衆的PWD」變量SecureString的?「 _ - 這看起來像一個[XY問題(HTTPS:/ /meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。你爲什麼想要這樣做呢? – CodeCaster

回答

6

從字符串構造這似乎違背使用SecureString背後的原則。見https://msdn.microsoft.com/en-us/library/system.security.securestring(v=vs.110).aspx

A SecureString object should never be constructed from a String, because the sensitive data is already subject to the memory persistence consequences of the immutable String class. The best way to construct a SecureString object is from a character-at-a-time unmanaged source, such as the Console.ReadKey method.