Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace password in connection string with regular expression in C#

Tags:

c#

regex

I'm trying to create a regular expression in C# that will replace the password of a connection string so that it is not shown when I display it on a page. The connection string password are somewhere in the string as PWD=password;

So far I have:

Regex.Replace(connStr, "PWD=.*;", "PWD=********");

This works to find the beginning of the pattern, but the problem is the wild card (.*) is also including the ; so the pattern is never terminated and the remainder of the string is replaced too. How can I say everthing but a ; in my RegEx?

Thanks.

like image 442
Paul Avatar asked Dec 02 '11 17:12

Paul


3 Answers

You don't need to use RegEx for this - .NET has the built-in SqlConnectionStringBuilder class which you can use to get values from the connection string and change them.

Example code:

string conString = "Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;";
var builder = new SqlConnectionStringBuilder(conString);

builder.Password = "********";

Console.WriteLine(builder.ToString());
like image 98
Christian Specht Avatar answered Nov 08 '22 09:11

Christian Specht


You can use a non-greedy quantifier:

PWD=.*?;

Or exclude ;s:

PWD=[^;]*;
like image 42
Ry- Avatar answered Nov 08 '22 09:11

Ry-


Here is the regex I'm using

(?<=Password=).+?(?=(;|'|"|$))

With positiv look behind to find the start of the password, positiv look ahead to find the end of the Password and a not greedy match Expression. The "Detektion Tokens" (Password= ;'"$) might differ in varios scenarios.

Testcases: https://regex101.com/

c# implementation

using System.Text.RegularExpressions;
private static Regex _regex = new Regex("(?<=Password=).+?(?=(;|'|\"|$))");
//...
var decryptPwdMatch = _regex.Match("some connectionstring for example");
//...

like image 36
user11879915 Avatar answered Nov 08 '22 10:11

user11879915