【发布时间】:2017-05-31 14:28:51
【问题描述】:
我在将 JSON 文本序列化为包含 SecureString 变量的对象时遇到问题。如何在将公共“pwd”变量保持为 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'
【问题讨论】:
-
将
pwd属性的类型改为string -
“同时将公共 'pwd' 变量保留为 SecureString?” - 这看起来像 XY problem。你为什么要首先这样做?
-
因为密码是要保存在 SecureString 中的机密,以避免被内存转储和类似攻击泄露。这表示 SecureString 没有默认的 json 序列化程序,它知道如何保密,因此还需要为 SecureString 实现一个自定义的 json 序列化程序,它会做一些类似加密的事情,这样生成的 json 就不会泄露秘密明文。
标签: c# .net json serialization json.net