Reputation: 18411
I'm printing command line arguments this way:
static void LogParameters(string[] args)
{
Console.WriteLine("Command line parameters: {0}", string.Join(" ", args);
}
Which will print -username=Scott -password=cafebabe -nofail
. But I would like to print it as:
-username=Scott -password=******* -nofail
How do I make that anything appears after password=
for this argument is printed with asterisks?
Upvotes: 3
Views: 4543
Reputation: 34189
I see two obvious ways to do this:
I would prefer the first one, using LINQ:
var argsForLogging = args
.Select(arg => arg.StartsWith("-password=") ? "-password=(entered)" : arg);
Console.WriteLine("Command line parameters: {0}", string.Join(" ", argsForLogging));
It may look not that good, but it is easily readable, and there are no regular expressions :)
P.S. It is possible to make the code output not (entered)
, but as many asterisks as there are letters in a password. However, it would still disclose very sensitive information.
Update:
If arguments format is not strict, then you need to take this into account.
For example, if it should be case-insensitive, then you may want to use this approach:
var argsForLogging = args
.Select(arg => arg.Trim().StartsWith("-password=", true, CultureInfo.InvariantCulture)
? "-password=(entered)"
: arg);
Console.WriteLine("Command line parameters: {0}", string.Join(" ", argsForLogging));
Upvotes: 3
Reputation: 26199
static void LogParameters(string[] args)
{
string msg = string.Empty;
foreach(var item in args)
{
var subParts = item.Split(new[] { '=' },
StringSplitOptions.RemoveEmptyEntries);
if (subParts[0] != "-password")
msg += item + " ";
else
msg += subParts[0] + "****** ";
}
Console.WriteLine("Command line parameters: {0}",msg.TrimEnd());
}
Upvotes: 1
Reputation: 1054
Normally
String maskString = String.Empty;
String replaceString = "-password=";
foreach (var item in args)
{
if (item.IndexOf(replaceString) >= 0)
{
maskString += replaceString + "********* ";
}
else
{
maskString += item+" ";
}
}
Console.WriteLine("Command line parameters: {0}", maskString.TrimEnd());
Or LinQ
var argsForLogging = args
.Select(arg => arg.StartsWith("-password=") ? "-password=*********" : arg);
Console.WriteLine("Command line parameters: {0}", string.Join(" ", argsForLogging));
Upvotes: 2