How can I encrypt only passwords in a web.config file?
<add name="PSystem" connectionString="Server=test;Database=Dev;User ID=testuser;Password=password#123;Trusted_Connection=False;Encrypt=True;" providerName="System.Data.SqlClient" />
I believe that built-in encryption mechanisms work on the entire connectionString section:
See this website for more info
If you would like to encrypt in-memory passwords, maybe entered by the user through a login form, you could use SecureString
you can try using flags in the connecction string as follows:
<add name="PSystem"
connectionString="Server=test;
Database=Dev;
User ID=#UserID#;
Password=#Password#;
Trusted_Connection=False;
Encrypt=True;"
providerName="System.Data.SqlClient" />
then you can have the encrypted user and password as follows:
<add key="DB_User" value = [Encrypted Username]>
<add key="DB_Password" value = [Encrypted Password]>
Then in code you just replace the flags:
string _connectionString = ConfigurationManager.ConnectionStrings["PSystem"].ConnectionString;
string user = Decrypt(ConfigurationManager.AppSettings["DB_User"]);
string password = Decrypt(ConfigurationManager.AppSettings["DB_Password"]);
_connectionString = _connectionString.Replace("##User##", user).Replace("##Password##", password);
To encrypt configuration file
contents, use the Aspnet_regiis.exe tool with the –pe option and the
name of the configuration element to be encrypted.
aspnet_regiis -pe "connectionStrings" -app "/SampleApplication" -prov
"RsaProtectedConfigurationProvider"
Source: http://msdn.microsoft.com/en-us/library/zhhddkxy(v=vs.100).aspx
Related
I'm trying to decrypt a Web.config section that was encrypted with RSA from an external Powershell script. The section goes:
<connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
<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>.......</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
<CipherValue>.......</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>
The code goes:
[xml]$x = Get-Content "$Path\Web.config"
$Prov = New-Object System.Configuration.RsaProtectedConfigurationProvider
$Prov.Decrypt($x.configuration.connectionStrings.EncryptedData)
It's executed via remote Powershell on the server where the config is. The account is an admin, so local machine keys should be available. And I'm getting an error:
Value cannot be null. Parameter name: keyName
An identical, modulo provider name, fragment works for DPAPI encrypted sections. The key name is right there in the section. What am I missing here?
Update: when the Web code does it, it calls Initialize() on the provider first. I've mimicked the parameters on that Initialize call. They come from machine. config.
$nv = New-Object System.Collections.Specialized.NameValueCollection
$nv.Add("description", "Uses RsaCryptoServiceProvider to encrypt and decrypt")
$nv.Add("keyContainerName", "NetFrameworkConfigurationKey")
$nv.Add("cspProviderName", "")
$nv.Add("useMachineContainer", "true")
$nv.Add("useOAEP", "false")
$Prov.Initialize("RsaProtectedConfigurationProvider", $nv)
Now I'm getting a different error: "Bad data".
Update 2: tried siccing aspnet_regiis on that file, got the same "Bad data" error. But the site itself seems up and running and database aware. Maybe the connectionString section is damaged after all, and the site takes it elsewhere.
I"m not sure about doing it via Powershell but here's what I do manually via code-behind on a web page. There might be a clue in here. I can delete this answer if it doesn't help.
protected void btnEncryptConnStrings_Click(object sender, EventArgs e)
{
// Open web.config file as a configuration object to get information.
Configuration objConfigFile = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
// Work with the <connectionStrings> section.
ConfigurationSection connectionStrings = objConfigFile.GetSection("connectionStrings");
if(connectionStrings != null)
{
// Only encrypt the section if it is not already protected.
if(!connectionStrings.SectionInformation.IsProtected)
{
// Encrypt the <connectionStrings> section using the
// DataProtectionConfigurationProvider provider (see notes at top of file).
connectionStrings.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider"); // alt: DataProtectionConfigurationProvider
objConfigFile.Save();
// other stuff.
}
}
}
In data layer I am trying to fetch connection string from app.config.
App.config
<connectionStrings>
<add name="DBConnection" connectionString="Data Source=****;Initial Catalog=****;Persist Security Info=True;User ID=*****; Password=***" />
</connectionStrings>
Fetching Value:
Shared _ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString
this is not working.
And I tried
Shared _ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings(0).ConnectionString
it is partially fetching - "Data Source=****;Initial Catalog=****;Persist Security Info=True"
Kindly explain.
Try using ConnectionStrings["DBConnection"].ConnectionString instead of ConnectionStrings("DBConnection").ConnectionString.
So i get the error that i should call WebSecurity.InitializeDatabaseConnection
before i call any function of the webSecurity Class
So i created _AppStart.cshtml and placed this code in it :
#using System.Configuration;
#{
string connString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
WebSecurity.InitializeDatabaseConnection(connString, "users", "id", "email", autoCreateTables: true);
}
and in Web.Config i got
<appSettings>
<add key="enableSimpleMembership" value="true" />
</appSettings>
<connectionStrings>
<add name="conString" providerName="System.Data.SqlClient"
connectionString="Data Source=(local)\SQLEXPRESS;Initial Catalog=sales;Integrated Security=True;Pooling=False"/>
</connectionStrings>
now i get this error from the InitializeDatabaseConncection method :
Connection string "Data Source=(local)\SQLEXPRESS;Initial Catalog=sales;Integrated Security=True;Pooling=False" was not found.
whats the problem ?
WebSecurity.InitializeDatabaseConnection is not asking you for a connection string. It's asking you for the name of the connection string. It will then retrieve the connection string form the configuration file for you.
WebSecurity.InitializeDatabaseConnection("conString", "users", "id", "email", autoCreateTables: true);
When you have a question about why a method is not behaving as expected, read the documentation! It states for that parameter:
The name of the connection string for the database that contains user information. If you are using SQL Server Compact, this can be the name of the database file (.sdf file) without the .sdf file name extension.
By default ASP.NET Identity user data is stored in an mdf file.
I want to store the data in a Sql database so that I changed the defaultconnection string in my web.config to my EF based connection:
<add name="DefaultConnection" connectionString="metadata=res://*/Models.StartifyModel.csdl|res://*/Models.StartifyModel.ssdl|res://*/Models.StartifyModel.msl;provider=System.Data.SqlClient;provider connection string="data source=MYPC\SQLEXPRESS;initial catalog=mydb;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Now I am getting the error The entity type ApplicationUser is not part of the model for the current context. as soon as I want to register a user.
I use the default MVC5 project template of VS2013.
Please try specify the connection string in the format:
<add name="DefaultConnection" connectionString="Data Source=127.0.0.1, 1433;Initial Catalog=YourDB;User Id=XXXX;Password=XXXXX;Asynchronous Processing=True;Encrypt=False;TrustServerCertificate=True;Persist Security Info=True" providerName="System.Data.SqlClient" />
And then make sure in Models/IdentityModels.cs you have
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
We developed an application to edit the web.config settings. The user has to locate the web.config file which they like to edit. Once their task is completed they can download the web.config file with the changes made by them. Since the web.config file has the database server information and passwords I have a concern that will it cause any security problem.
If so how can I rectify it?
Better encrypt your Connection string....
For ref MSDN article
You can use the following method to secure the the webconfig.
if there exist the following code at web.config.
<connectionStrings>
<add name="yjsDBConnectionString" connectionString="Data Source=HUAJLI-XP\SUN;Initial Catalog=yjsDB;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Then we can use the following code to protect it.
protected void Encryption()
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.ConnectionStrings;
if (!section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
section.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);
}
}
And you can use the following code to Decrypting it.
protected void Decrypting()
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.ConnectionStrings;
if (section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
section.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);
}
}