65.9K
CodeProject is changing. Read more.
Home

Remove the security credentials from a connection string

starIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

1.00/5 (1 vote)

Jun 25, 2009

CPOL
viewsIcon

23043

downloadIcon

54

This might save you 15 minutes and avoid the embarrasment of returning your 'sa' password to your customers along with an error message.

Introduction

This is a noddy app with a method to remove the security credentials from a database connection string.

Background

It's the sort of thing that you have to write over and over wherever you go and is always more time consuming than you would think.

Using the code

Feel free to use this - add more security qualifiers if you like too - at present, the example only hits user, uid, pwd, and password.

The main method is as follows - so no need to download the code:

string m_DatabaseConnectionString = 
  "Data Source=MYHAPPYHAPPYDB\\SQLEXPRESS;Initial Catalog=JoyJoy;user=sa;password=W@nk3r";

private string RemoveConnectionStringSecurity(string inString)
{
    string[] securityQualifiers = new string[] { "user", "uid", 
                                      "password", "pwd" };
    string retStr = m_DatabaseConnectionString;

    foreach (string qualifier in securityQualifiers)
    {
        if (retStr.IndexOf(qualifier + "=") > 0)
        {
        // Remove Security Qualifier
            try
            {
                retStr = retStr.Substring(0, 
                         retStr.ToLower().IndexOf(qualifier + "=") + 
                         qualifier.Length + 1)
                        + "*HIDDEN*"
                        + retStr.Substring
                        (
                            retStr.ToLower().IndexOf(qualifier + "="),
                            retStr.Length - retStr.ToLower().IndexOf(qualifier + "=")
                        ).Substring
                        (
                            retStr.Substring
                            (
                                retStr.ToLower().IndexOf(qualifier + "="),
                                retStr.Length - retStr.ToLower().IndexOf(qualifier + "=")
                            ).IndexOf(";")
                        );
            }
            catch
            {
            // Last element and no terminating ';'
                retStr = retStr.Substring(0, 
                  retStr.ToLower().IndexOf(qualifier + "=") + qualifier.Length + 1)
                  + "*HIDDEN*";
            }
        }
    }

    return inString.Replace(m_DatabaseConnectionString, retStr);
}