在我的.net网络应用程序中,我加密了web.config文件。
但是现在我需要从外部winforms应用程序读取此加密连接String并将结果显示在文本框中。文本框文本看起来像这样:
<connectionStrings configProtectionProvider="CustomEncryptProvider">
<EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<KeyName>Rsa Key</KeyName>
</KeyInfo>
<CipherData>
<CipherValue>Smbfcf3dHbuYZ34hLWtATU8fBqNL/CvPk24tLj9gLOizLzV88den52yhtYQ5AwXe2vVZP/GKRsWB+rcX/6ufBkz75HyVOnJHTCgLQ+JcsRX/9Td5ZzWJrEq1JBdpFzBsS9aLGLMREIILPedmFxO5+0GLIaBPzZ9/BhNcN8GXa+k=</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
<CipherValue>raoQqDzlXmMCy+3VliV6oyMoQzgIapSmBKw666WbUjLgurCh4aS+pwSMW3wULOpi+jh8BdDE/aPwvhDw9kTuComyHBsEB4xMtRFaBY1NSyrwx7dnP44x4NS+LowJ1EQiN2fAZqWDDVAljRIlq3DtZhC9YkYl4H1rEjQVvljD0pus1O8ftiqKy/yma1/rqzI+F/87GrFR1ZM8cS/ujXagtfzqME4iVdTgl/eyEPkrd5f6SGwlieeC0zJ2ErV9zIr+Af2Sc6mk2hz7/+t2x3kAzDzHU2PFfBqiLSP6o/0XAdRl43Q/Jwr72552mus7n5urlzvyND0KXKzk4Gg4bVYuo8sSQvphbFuLgHIxq+6ShDdCc9wfMzsBmGU4ayYbn/a4rI8lB5y6GzK0kQvnH0qtWQ==</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>
如何实现同样的目标?请注意我只有web.config文件的物理路径。
答案 0 :(得分:1)
您可以使用System.Configuration.ConfigurationManager
加载配置文件,如下所示:
var config = ConfigurationManager.OpenExeConfiguration(/* path to config file */);
连接字符串将自动解密,并且可以在ConnectionStrings
对象的Configuration
属性中使用。在您的情况下,连接字符串被称为&#34; LocalSqlServer&#34;:
Console.WriteLine(config.ConnectionStrings.ConnectionStrings["LocalSqlServer"]);
> data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
修改强>
如果您已经指出,您实际上想要connectionStrings
xml元素的全部内容,则可以使用XmlReader
执行此操作:
using (var reader = XmlReader.Create(/* path to config file */))
{
if (reader.ReadToDescendant("connectionStrings"))
Console.WriteLine(reader.ReadOuterXml());
}
> <connectionStrings configProtectionProvider="CustomEncryptProvider"> <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element" etc...