Mask a String Using Linq Aggregate Method

There are a lot of different ways to mask sensitive data like passwords and account numbers when displaying to users.  Most of them seem to include some sort of loop and/or a regular expression and get the job done. Recently, I wrote a simple function using Linq that I thought was worth sharing.

Here it is:

public static string MaskString(this string stringToMask, string mask, 
 int show)
{
     return stringToMask.ToCharArray().Aggregate("", (maskedString, nextValueToMask) 
          => maskedString + (maskedString.Length < stringToMask.Length - show 
          ? mask : nextValueToMask.ToString()));
}

Explanation:
The function takes in the string being masked, the masking character, and the number of characters to show. It assumes the masking starts on the left and it is written as an extension method.

It’s pretty simple really. The string is converted to an array so the Linq Aggregate function can be used to string the array back together replacing each character along the way with the mask until the show point in the string is reached.

More Info:
The Aggregate function was brought to my attention in a blog post from  By A Tool.  I’ve used variations of this for combining lists of strings and removing duplicates from delimited strings for a system I’ve been working on.  Just for fun I included those below to demonstrate other applications of the aggregate function.

More Aggregate Examples:

public static string CombineListToDelimitedString(this List<String>listOfStrings, 
     string delimiter)
{
 return listOfStrings.Distinct().Aggregate("", (inner, outer) => inner +
         (!inner.Contains(outer.ToString()) ? outer.ToString() + delimiter : "")).TrimEnd( 
 new char[] { Convert.ToChar(delimiter) });
}

public static string RemoveDuplicatesFromDelimitedString(this string delimitedString,
 string delimiter)
{
 return delimitedString.Split(new char[] { Convert.ToChar(delimiter) }).Distinct().Aggregate("", (inner, outer) => inner
         + (!inner.Contains(outer.ToString()) ? outer.ToString() + delimiter : "")     ).TrimEnd(
         new char[] { Convert.ToChar(delimiter) });
}

Conclusion:
Linq never seems to disappoint when looking for a cleaner and cooler looking way of doing things. It just goes to show, there are more than two ways to skin a cat. Or in this case, “mask” a cat.

Yep, that just happened…

Advertisements

About Shawn Sweeney

I'm a father, software developer, and runner. I blog about things related. View all posts by Shawn Sweeney

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: