序列化对象时如何加密选定的属性? [英] How can I encrypt selected properties when serializing my objects?

查看:75
本文介绍了序列化对象时如何加密选定的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JSON将某些设置存储在我的应用程序中.一些设置包含敏感信息(例如密码),而其他设置则不敏感.理想情况下,我希望能够序列化敏感属性被自动加密的对象,同时保持非敏感设置的可读性.有没有办法使用Json.Net做到这一点?我没有看到任何与加密相关的设置.

I'm using JSON to store certain settings within my application. Some of the settings contain sensitive information (e.g. passwords) while other settings are not sensitive. Ideally I'd like to be able to serialize my objects where the sensitive properties are encrypted automatically while keeping the non-sensitive settings readable. Is there a way to do this using Json.Net? I did not see any setting related to encryption.

推荐答案

我的解决方案:

    public string PasswordEncrypted { get; set; }

    [JsonIgnore]
    public string Password
    {
        get
        {
            var encrypted = Convert.FromBase64String(PasswordEncrypted);
            var data = ProtectedData.Unprotect(encrypted, AdditionalEntropy, DataProtectionScope.LocalMachine);
            var res = Encoding.UTF8.GetString(data);
            return res;
        }
        set
        {
            var data = Encoding.UTF8.GetBytes(value);
            var encrypted = ProtectedData.Protect(data, AdditionalEntropy, DataProtectionScope.LocalMachine);
            PasswordEncrypted = Convert.ToBase64String(encrypted);
        }

(可以减少冗长)

这篇关于序列化对象时如何加密选定的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆