我想创建一个通用方法来屏蔽 json 文档中的密码属性。如何设置元素值?
private void MaskPassword(string json)
{
var node = JsonNode.Parse(json);
if (node is JsonArray)
{
var arr = JsonSerializer.Deserialize<JsonArray>(json);
foreach(var item in arr)
{
MaskPassword(item.ToJsonString());
}
}
else
{
var document = JsonSerializer.Deserialize<JsonDocument>(json);
foreach (JsonProperty property in document.RootElement.EnumerateObject())
{
if (property.Name.Contains("password", StringComparison.OrdinalIgnoreCase) &&
property.Value.ValueKind == JsonValueKind.String)
{
var strValue = property.Value.GetString();
if (!string.IsNullOrWhiteSpace(strValue))
{
property.Value = new string('*', strValue.Length); //how to set the value here?
}
}
}
json = document.RootElement.ToString();
}
}
您可以像此示例一样对密码进行编码
string original = "yourpassword!";
string encrypted =Convert.ToBase64String(Encoding.UTF8.GetBytes(original));
当然,你也可以让它变得复杂,例如:256位加密或AES等...
然后,将其作为参数输入,这行代码:
property.Value = new string('*', strValue.Length);
至:
property.Value = decrypt(encrypted);