Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / .NET / .NET4.5

Storing Your Connection String Password in SecureString

4.90/5 (7 votes)
23 Jun 2012CPOL1 min read 29.2K  
This trick can provide some extra protection for your passwords used in connection strings against runtime attacks.

Introduction

Strings have always been quite interesting for hackers. I have wrote an article about its reasons that could be found here. One of the key victims of this type of attack is ConnectionStrings in memory primarily because it can have database credentials. Typically developers use classes like SqlConnectionStringBuilder or OracleConnectionStringBuilder etc. to build connection strings. The problem is that these classes expose string type Password property to set the password for authenticating users. As I mentioned in my other article (why hackers love string data types), Microsoft has provided SecureString class that provides some protection against runtime attacks targeting strings in memory. However, we couldn't have used this SecureString in context of connection string as the classes like SqlConnectionStringBuilder, OracleConnectionStringBuilder, etc., were still using string data type for password field. With .NET 4.5, this is going to change. In .NET 4.5, Microsoft has introduced a class called SqlCredential. As you can seen below, its constructor takes a SecureString type for password.

C#
public SqlCredential( string userId,  SecureString password )

So now developers have the ability to use SecureString for storing password in connection strings when using SQL authentication. Of course, if possible, using Windows authentication should be preferable as it is more secure.

Lastly, let me be very clear about SecureString, people have found ways of working around SecureString too, so I am not saying that it is perfectly safe, however, it does make cracking a password a bit more difficult (at least for causal hackers).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)