Reputation: 61
I have an console application, where I should connect to a SQL Server. It is protected by password.
I have to decrypt only the password value from the <connectionStrings>
tag like
<add name="ConnectionStringname"
connectionString="Data Source=xx.x.x.xx;Initial Catalog=DbName;User ID=xxx;Password="DecryptedValueOfPasword" />
I have tried these approaches, please let me know which one is the best or any other approaches please let me know.
Approach 1 : encrypt and decrypt the whole <connectionStrings>
tag using this command
aspnet_regiis -pef connectionStrings "app.config Path"
Approach 2 : encrypt and decrypt the only the password value
Step 1 : Removed password value from the connection strings and password value added in custom tag.
<add name="ConnectionStringname"
connectionString="Data Source=xx.x.x.xx;Initial Catalog=DbName;User ID=xxx;" />
Step 2 : decrypting the custom tag using the RSA key i.e using the aspnet_regiis.exe
command .
Step 3 : in the code-behind file, read the decrypted password value and append the password value in connection string
<add name="ConnectionStringname"
connectionString="Data Source=xx.x.x.xx;Initial Catalog=DbName;User ID=xxx;Password="EncryptedValueOfPasword" />
Approach 3 : create class library
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);
}
}
Upvotes: 2
Views: 4531
Reputation: 129
Use XML instead of config file.store your credentials in XML file and encrypt password in XML file and get from there
<?xml version="1.0" encoding="utf-8" ?>
<Connections>
<UserId>sa</UserId>
<Password>DecryptedValueOfPasword</Password>
</Connectionstring>
Something like above
Upvotes: 0
Reputation: 2258
First of all I don't understand why do you have to decrypt only the password value? Other parts of connection string represent security information like db name, or user id. So you have to encrypt whole connection string, not only a part of it.
Approach 1 is the best option as it has the following benefits:
aspnet_regiis -pd "connectionStrings"
Upvotes: 2