如何在C#中仅加密和解密ConnectionString Web.config/App.config中的密码?
我有一个控制台应用程序,我应该在那里连接到SQL Server。它受密码保护 我必须只解密如何在C#中仅加密和解密ConnectionString Web.config/App.config中的密码?,c#,encryption,configuration,cryptography,C#,Encryption,Configuration,Cryptography,我有一个控制台应用程序,我应该在那里连接到SQL Server。它受密码保护 我必须只解密标记中的密码值,如 <add name="ConnectionStringname" connectionString="Data Source=xx.x.x.xx;Initial Catalog=DbName;User ID=xxx;Password="DecryptedValueOfPasword" /> 方法2:仅对密码值进行加密和解密 步骤1:从连接字符串中删除密码值,并
标记中的密码值,如
<add name="ConnectionStringname"
connectionString="Data Source=xx.x.x.xx;Initial Catalog=DbName;User ID=xxx;Password="DecryptedValueOfPasword" />
方法2:仅对密码值进行加密和解密
- 步骤1:从连接字符串中删除密码值,并在自定义标记中添加密码值
<add name="ConnectionStringname" connectionString="Data Source=xx.x.x.xx;Initial Catalog=DbName;User ID=xxx;" />
public class EncryptDecryptClass {
public string Encrypt(string plainText)
{
if (plainText == null)
throw new ArgumentNullException("plainText");
//encrypt data
var data = Encoding.Unicode.GetBytes(plainText);
byte[] encrypted = ProtectedData.Protect(data, null, Scope);
//return as base64 string
return Convert.ToBase64String(encrypted);
}
public string Decrypt(string cipher)
{
if (cipher == null)
throw new ArgumentNullException("cipher");
//parse base64 string
byte[] data = Convert.FromBase64String(cipher);
//decrypt data
byte[] decrypted = ProtectedData.Unprotect(data, null, Scope);
return Encoding.Unicode.GetString(decrypted);
}
}
首先,我不明白为什么你必须只解密密码值?连接字符串的其他部分表示安全信息,如db名称或用户id。因此,您必须加密整个连接字符串,而不仅仅是其中的一部分 方法1是最佳选择,因为它具有以下好处:
aspnet\u regiis-pd“ConnectionString”
使用XML而不是配置文件。将凭据存储在XML文件中,并在XML文件中加密密码,然后从中获取信息
<?xml version="1.0" encoding="utf-8" ?>
<Connections>
<UserId>sa</UserId>
<Password>DecryptedValueOfPasword</Password>
</Connectionstring>
sa
密码的解密值
类似上面的内容谢谢你的回答。我只想解密密码值。如果要解密app.config中的connectionString标记,请使用第1种方法将app.config重命名为web.config,然后执行命令并再次将web.config重命名为app.config。
public class EncryptDecryptClass {
public string Encrypt(string plainText)
{
if (plainText == null)
throw new ArgumentNullException("plainText");
//encrypt data
var data = Encoding.Unicode.GetBytes(plainText);
byte[] encrypted = ProtectedData.Protect(data, null, Scope);
//return as base64 string
return Convert.ToBase64String(encrypted);
}
public string Decrypt(string cipher)
{
if (cipher == null)
throw new ArgumentNullException("cipher");
//parse base64 string
byte[] data = Convert.FromBase64String(cipher);
//decrypt data
byte[] decrypted = ProtectedData.Unprotect(data, null, Scope);
return Encoding.Unicode.GetString(decrypted);
}
}
<?xml version="1.0" encoding="utf-8" ?>
<Connections>
<UserId>sa</UserId>
<Password>DecryptedValueOfPasword</Password>
</Connectionstring>