how to do masking/hiding email address in c#

Here is a approach to solve this with Regex

string input = "[email protected]";
string pattern = @"(?<=[\w]{1})[\w-\._\+%]*(?=[\w]{1}@)";
string result = Regex.Replace(input, pattern, m => new string('*', m.Length));
//j**[email protected]

Explanation:

(?<=[\w]{1}) the name has to start with 1 word-character

[\w-\._\+%]* the replacement-part can contain 0-n word characters including -_.+%

(?=[\w]{1}@) the name has to end with one word character followed by a @

Depending on the amount of characters you want to remain unchanged you can change {1} to {2} or something else at the beginning or at the end.


If you always want to mask anything between first character and last character before @ with fixed number of masked characters , you can use the below

var email="[email protected]";
var maskedEmail = string.Format("{0}****{1}", email[0], 
email.Substring(email.IndexOf('@')-1));

You can alter the above line for your requirement.

The above line will give you the result "a****[email protected]"

Note that masking the email always with a fixed number of characters will make it difficult to guess the email and is slightly more secure.

ex: [email protected]

after mask: a****[email protected]


I can't see where your k variable is initialised in your code snippet. If I had to take a wild stab as to why you are getting an index out of bounds exception that would be my stab.

Although I would say that you could achieve something very similar to what you are doing using Regex. I did it like this:

public string ObfuscateEmail(string email)
{
    var displayCase = email;

    var partToBeObfuscated = Regex.Match(displayCase, @"[^@]*").Value;
    if (partToBeObfuscated.Length - 3 > 0) {
        var obfuscation = "";
        for (var i = 0; i < partToBeObfuscated.Length - 3; i++) obfuscation += "*";
        displayCase = String.Format("{0}{1}{2}{3}",  displayCase[0], displayCase[1], obfuscation, displayCase.Substring(partToBeObfuscated.Length - 1));
    } else if (partToBeObfuscated.Length - 3 == 0) {
        displayCase = String.Format("{0}*{1}", displayCase[0], displayCase.Substring(2));
    }

    return displayCase;
}

Here is a fiddle of all your test cases provided passing pretty close to what you were describing https://dotnetfiddle.net/fU2RUo

[EDIT] My code doesn't try to obfuscate emails whose addresses before the @ are less than 3 characters long, if this is a requirement you would need to amend the code but I didn't think it was a very realistic case to have to build a case for.