I want to encrypt the password in connection string. When I make a connection to DB the connection string is openly stored in App.config and I need to find a way to keep only password encrypted.
Lets say this is your connection string:
<connectionStrings>
<add name="cs" connectionString="Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=XXSDFASFDKSFJDKLJFDWERIODFSDFHSDJHKJNFJKSD;"/>
</connectionStrings>
Then you can do something like this:
string myCs = System.Configuration.ConfigurationManager.ConnectionStrings["cs"].ConnectionString;
System.Data.SqlClient.SqlConnectionStringBuilder csb = new System.Data.SqlClient.SqlConnectionStringBuilder(myCs);
csb.Password = EncDecHelper.Decrypt(csb.Password);
myCs = csb.ToString();
You can write EncDecHelper.Decrypt by using samples from here: Encrypt and decrypt a string
Use the connectionStrings configuration section and encrypt the whole section - instead of just the password.
This is safer as your app config will no longer have the server names and user names in plain text either.
There are how-to documents for encrypting configuration sections on MSDN for RSA or DPAPI.
Maybe decrypt connection string from your config before application was loaded.
As an addition to the other answers, isn't it better to use the file in Source Control as a template, with just dev/test encrypted connection strings so that it works in dev/test.
For production (or other environments the app is deployed to), the encrypted credentials file is generated separately to the specified template format, managed/updated/deployed separately, has appropriate security permissions applied, never seen by anyone other than DBA/DevOps.
Related
If I want to make a C# login form, with a Mysql databse which provides the userdata, in c#, i would say it's unsafe to write the database password, database username and database name in the connection string. Am i right? And is there another way like a webserver which will connect to the database and check if userdata is right?
You should store such things in a configuration file. .NET has the option to use encryption in web.config / app.config.
https://msdn.microsoft.com/en-us/library/ms254494(v=vs.110).aspx#Anchor_2
Either way you will have to provide those credentials. You can pass them in connection string in your code (OR) can have those maintained in web.config or app.config file in which case you can actually encrypt the password and have the encrypted value mentioned in connection string.
Right now we need a secure place to put our connection strings. We would like to place these connection strings in an external file separate from Web.config to make deployments easier, but we also want the information inside to be encrypted for security.
Is there any way to accomplish this using the Aspnet_regiis tool? I understand how to use it to encrypt sections within the Web.config file, and we like how encrypting with this method means that decryption happens for us automatically when the site is being used. But the information I find on this subject seems conflicting.
Encrypt custom config section in ASP.NET using aspnet_regiis
This link to another question seems to suggest that all I have to do is set the external config file up like normal, place the sensitive connection string info inside of it, and run the Aspnet_regiis tool as normal and the external file will be encrypted.
http://www.velocityreviews.com/forums/t722875-encrypting-external-config-section.html
However the response in that link states that Aspnet_regiis cannot be used to encrypt external sections.
So can this be done, and if not, is doing all of this programatically the only way to go?
I just tried this myself, and I can confirm that the Aspnet_regiis tool WILL indeed encrypt connection strings stored in an external config file. In the Web.config file I referred to the externally-defined connection strings using the "configSource" attribute, and they were encrypted after running the tool.
You can encrypt connection string using C#
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = modulePath + "Web.Release.config";
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
System.Configuration.ConfigurationSection section = config.GetSection("connectionStrings");
if (!section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
config.Save();
}
I have the following connection string:
Data Source=Paul-HP\MYDB;Initial Catalog=MyMSDBSQL;Persist Security Info=True;User ID=sa;Password=password
(.net webservice)
This can obviously be viewed simply by opening up the app.config file and looking at the configuration settings.
What I need is a way to make a hacker unable to see the password. But at the same time, leave it customisable so that it can be changed when deployed on another database.
You have a number of options - the ones that I am aware of (in order of preference):
Use integrated (SSPI) security where you don't need to include a password in the config file
Encrypt the connection string (see Encrypting Configuration Information Using Protected Configuration)
Store the username and password separately and use string formatting to construct the full connection string,
So for example the connection string might look like this:
Data Source=Paul-HP\MYDB;Initial Catalog=MyMSDBSQL;Persist Security Info=True;User ID={0};Password={1}
I'd go for option 1, if thats not possible then option 2. I've mentioned option 3 for completeness.
Have you read Protecting Connection Information (ADO.NET)?
First of all, don't use the "SA" account. It leaves your database wide open if someone gets the password. Use a custom account which only is allowed to do CRUD operations on a specific database.
The only way to get web.config is to hack your server. And if they have done that, you're screwed anyway.
Probably easiest to encrypt the connection strings within the web.config or app.config
See How To: Encrypt Configuration Sections in ASP.NET 2.0 Using DPAPI
I Suggest en/decrypting the connection string. Therefore the connection string has to be set manually.
For encryption take a look at:
http://dotnet-snippets.de/dns/encrypt-and-decrypt-strings-SID205.aspx
For Custom Settings take a look at:
http://msdn.microsoft.com/en-us/library/8eyb2ct1.aspx
Replace the Encrypted with the correct one at runtime:
public static void SetAppSettingValue(string Key, string Value)
{
System.Configuration.Configuration config == ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Add an Application Setting.
config.AppSettings.Settings[Key].Value = Value;
// Save the changes in App.config file.
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
You could encrypt the connection string - then when you access the connection string, decrypt it. This isn't fool proof though as you're then stuck with the problem of where to store the key to decrypt the connection string!
How To Use Symmetric Key To Encrypt Connection String in Web.config file And What the Code for doing that (with libraries)
use System.Configuration.RsaProtectedConfigurationProvide
Encrype your connection string with simple application. and then add it to your main application. this will use machine key. it will work only with one server, where you have created thsi encryped connection string.
Protecting Connection Strings and Other Configuration Information
First, forgive my english.
My group and I are planning to do an application. This application can be installed to other machines, and should connect to a server and the database is password protected.
As a student, we always do this in a naive way:
SqlConnection myConnection = new SqlConnection("user id=username;" +
"password=password;server=serverurl;" +
"database=database; " +
"connection timeout=30");
Always hardcoded.
What if we change the password of the database, or chage our server?
We have also to change the values in our code, recompile and reinstall the application in the pc. Is there something dynamic way of doing these?
We are thinking that in the first run of the application, the user will be prompted for the connection details and save that data into a file where the application will fetch it everytime it starts and use it for database connection, but there's a password involved.
Any suggestion, ideas, concepts, samples, etc...? How to do it in more professional way? Please help... Thanks.
You could store the database settings in app.config
http://www.ezzylearning.com/tutorial.aspx?tid=8067328
you could store your credentials in the config file - that way no need to recompile the project every time the password changes.
The config file can be encrypted too, so you could only change the password via the application you're making.
Windows lets you encrypt files, so that only processes running as the owner can read them. You could store the passwords in a file and encrypt it. See File.Encrypt on MSDN.
This would only be one factor in the security model. You probably also want to encrypt the file at the application level so malicious software that the users run doesn't sniff around for passwords.
There are several ways to do this. First off all you may save your connectionString in an app.Config/web.config file. Your connection objects may access this string by using
PROJECTNAME.Properties.Settings.Default.YOURCONNECTIONSTRINGNAME
Your app.config file may look something like this
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="Winforms_Demo.Properties.Settings.dbNordwindConnectionString"
connectionString="Data Source=(local)\SQLEXPRESS;Initial Catalog=dbNordwind;User ID=sa"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
As you can see this possibility still saves any user credentials hardcoded (although you may change them by manually editing the config.file (even after compiling). You may create such a config file by adding a new datasource to your project (e.g. sql server datasource). The wizard will then ask where to save your connectionString.
Another possibility will be connectionStringBuilder. This class offers some properties:
SqlConnectionStringBuilder conbuild = new SqlConnectionStringBuilder();
conbuild.InitialCatalog = "dbNordwind"; // database name
conbuild.IntegratedSecurity = false; // true if you use winAuthent
conbuild.UserID = "sa"; // e.g get this info by showing a authent form
conbuild.Password = "123";
conbuild.DataSource = "servername";
SqlConnection con = new SqlConnection(conbuild.ConnectionString);
Using this method you may even access a file and read any required data. In this case you have to look into security measures for your file!
Securing your file may be done by encrypting it (System.Security namespace) or saving data into any isolatedStorage (user specific - windows security will be used) or by using "aspnet_regiis -pef" to crypt any config-file.