gpt4 book ai didi

c# - 在将类保存到 xml 文件之前加密属性

转载 作者:行者123 更新时间:2023-12-04 11:00:38 24 4
gpt4 key购买 nike

我正在尝试将一些连接字符串作为加密文本保存到我类(class)的 XML 中。

这是我的课:

using System.Data.SqlClient;
using TechGuyComputing.CompleteOrganizerWPF.Data;

namespace TechGuyComputing.CompleteOrganizerWPF.MiscClasses
{
public class AppSetting
{
private string _dataSource;
private string _intitialCatalog;
private string _userId;
private string _password;

public string DataSource
{
set => _dataSource = Encryption.SimpleEncryptWithPassword(value, GlobalConstants.EncryptionPassword);
get => Encryption.SimpleDecryptWithPassword(_dataSource, GlobalConstants.EncryptionPassword);
}

public string IntitialCatalog
{
set => _intitialCatalog = Encryption.SimpleEncryptWithPassword(value, GlobalConstants.EncryptionPassword);
get => Encryption.SimpleDecryptWithPassword(_intitialCatalog, GlobalConstants.EncryptionPassword);
}

public string UserId
{
set => _userId = Encryption.SimpleEncryptWithPassword(value, GlobalConstants.EncryptionPassword);
get => Encryption.SimpleDecryptWithPassword(_userId, GlobalConstants.EncryptionPassword);
}

public string Password
{
set => _password = Encryption.SimpleEncryptWithPassword(value, GlobalConstants.EncryptionPassword);
get => Encryption.SimpleDecryptWithPassword(_password, GlobalConstants.EncryptionPassword);
}

public bool IntegratedSecurity { set; get; }
public bool MultipleActiveResultSets { set; get; }
public bool PersistSecurityInfo { set; get; }
}

internal static class AppSettings
{
public static AppSetting ApplicationSettings;

public static SqlConnection ConnectionString { get; private set; }


static AppSettings()
{
if (ApplicationSettings == null)
{
ApplicationSettings = XmlReader.GetAppSettingsFromXmlFile();
SetConnectionString();
}
}

public static void SaveAppSettings()
{
if (ApplicationSettings == null)
{
ApplicationSettings = new AppSetting();
}
XmlReader.WriteAppSettingsToXmlFile(ApplicationSettings);
SetConnectionString();
}

private static void SetConnectionString()
{
if (string.IsNullOrEmpty(ApplicationSettings.DataSource) || string.IsNullOrEmpty(ApplicationSettings.IntitialCatalog))
{
ConnectionString = new SqlConnection();
return;
}

var builder = new SqlConnectionStringBuilder
{
DataSource = ApplicationSettings.DataSource,
InitialCatalog = ApplicationSettings.IntitialCatalog,
IntegratedSecurity = ApplicationSettings.IntegratedSecurity,
MultipleActiveResultSets = ApplicationSettings.MultipleActiveResultSets,
PersistSecurityInfo = ApplicationSettings.PersistSecurityInfo,
UserID = ApplicationSettings.UserId,
Password = ApplicationSettings.Password
};

ConnectionString = new SqlConnection(builder.ConnectionString);
}

}
}

这就是我保存 XML 文件的方式:
using System.IO;
using System.Xml.Serialization;

namespace TechGuyComputing.CompleteOrganizerWPF.MiscClasses
{
internal static class XmlReader
{

public static void WriteAppSettingsToXmlFile(AppSetting appSetting)
{
var xs = new XmlSerializer(typeof(AppSetting));
var tw = new StreamWriter(GlobalConstants.XmlFile);
xs.Serialize(tw, appSetting);
}

public static AppSetting GetAppSettingsFromXmlFile()
{
if (!File.Exists(GlobalConstants.XmlFile))
{
return new AppSetting();
}

using (var sr = new StreamReader(GlobalConstants.XmlFile))
{
XmlSerializer xs = new XmlSerializer(typeof(AppSetting));
return (AppSetting)xs.Deserialize(sr);
}
}


}
}

我的保存工作正常,但它没有将值保存为加密字符串。

我认为这会即时处理它,但它什么也没做:
public string DataSource
{
set => _dataSource = Encryption.SimpleEncryptWithPassword(value, GlobalConstants.EncryptionPassword);
get => Encryption.SimpleDecryptWithPassword(_dataSource, GlobalConstants.EncryptionPassword);
}

我没有收到任何错误消息,只是没有加密数据。

有什么建议我如何在保存某些属性之前对其进行加密?

编辑:
如果可以防止它,我宁愿不加密整个文件。我只想加密我选择的属性。

最佳答案

你的问题是 XmlSerializer仅序列化 公众 属性和字段——以及 AppSetting 中的公共(public)属性类都是未加密的。来自 docs

XML serialization serializes only the public fields and property values of an object into an XML stream. ...

XML serialization does not convert methods, indexers, private fields, or read-only properties (except read-only collections). To serialize all an object's fields and properties, both public and private, use the DataContractSerializer instead of XML serialization.



因此,您的选择是:
  • 为加密成员创建公共(public)属性并用 XmlIgnore 标记明文属性像这样:
    [System.ComponentModel.Browsable(false), System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never), System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
    [XmlElement("DataSource")] // Optionally change the element name to be <DataSource>
    public string EncryptedDataSource { get; set; }

    [XmlIgnore]
    public string DataSource
    {
    set => EncryptedDataSource = Encryption.SimpleEncryptWithPassword(value, GlobalConstants.EncryptionPassword);
    get => Encryption.SimpleDecryptWithPassword(EncryptedDataSource, GlobalConstants.EncryptionPassword);
    }

    演示 fiddle #1 here .
  • 切换到 DataContractSerializer .首先修改你的类如下:
    [DataContract]
    public class AppSetting
    {
    [DataMember(Name = "DataSource")]
    private string _dataSource;
    [DataMember(Name = "IntitialCatalog")]
    private string _intitialCatalog;
    [DataMember(Name = "UserId")]
    private string _userId;
    [DataMember(Name = "Password")]
    private string _password;

    // Remainder unchanged

    然后修改XmlReader如下:
    public static void WriteAppSettingsToXmlFile(AppSetting appSetting)
    {
    var serializer = new DataContractSerializer(typeof(AppSetting));
    using (var stream = new FileStream(GlobalConstants.XmlFile, FileMode.Create))
    {
    serializer.WriteObject(stream, appSetting);
    }
    }

    public static AppSetting GetAppSettingsFromXmlFile()
    {
    if (!File.Exists(GlobalConstants.XmlFile))
    {
    return new AppSetting();
    }
    using (var stream = File.OpenRead(GlobalConstants.XmlFile))
    {
    var serializer = new DataContractSerializer(typeof(AppSetting));
    return (AppSetting)serializer.ReadObject(stream);
    }
    }

    生成的属性都将被加密。

    演示 fiddle #2 here .

  • 笔记:
  • WriteAppSettingsToXmlFile()您不处置 StreamWriter .这将使文件保持打开状态,并可能在以后导致错误。相反,请执行以下操作:
    public static void WriteAppSettingsToXmlFile(AppSetting appSetting)
    {
    var xs = new XmlSerializer(typeof(AppSetting));
    using (var tw = new StreamWriter(GlobalConstants.XmlFile))
    {
    xs.Serialize(tw, appSetting);
    }
    }
  • 而用 XmlSerializer 序列化的属性必须公开,您可以通过使用 [Browsable(false)] 标记它们来稍微隐藏它们, [EditorBrowsable(EditorBrowsableState.Never)] [DebuggerBrowsable(DebuggerBrowsableState.Never)] ,
  • 关于c# - 在将类保存到 xml 文件之前加密属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58824043/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com