how to do masking/hiding email address in c#

19,351

Solution 1

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.

Solution 2

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]

Solution 3

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.

Solution 4

I wanted to mask emails like this A****B@C****D.com. This also works with emails that have multiple dots or no domain extension.

public string MaskEmail(string email)
{
    if (string.IsNullOrEmpty(email) || !email.Contains("@"))
        return email;

    string[] emailArr = email.Split('@');
    string domainExt = Path.GetExtension(email);

    string maskedEmail = string.Format("{0}****{1}@{2}****{3}{4}",
        emailArr[0][0],
        emailArr[0].Substring(emailArr[0].Length - 1),
        emailArr[1][0],
        emailArr[1].Substring(emailArr[1].Length - domainExt.Length - 1, 1),
        domainExt
        );

    return maskedEmail;
}

Results

[email protected]          >>  i****o@s****w.com
[email protected]                   >>  m****e@g****e.nl
[email protected]  >>  w****r@s****w.org
test@noextension               >>  t****t@n****n
[email protected]                        >>  x****x@y****y.net

Solution 5

I wrote this method as it was easier to customize for my specific masking requirements.

I hope this helps someone. If so, please mark the answer helpful.

public static string MaskEmail(this string email)
    {            
        var emailsplit = email.Split('@');
        var newsplit = emailsplit[1].Split('.');
        char[] array1 = emailsplit[0].ToCharArray();
        char[] array2 = newsplit[0].ToCharArray();
        var output = "";

        for (int i = 0; i < array1.Length; i++)
        {
            if (array1.Length > 4)
            {
                if (i == 0 || i == array1.Length - 1 || i == array1.Length - 2)
                {
                    output += array1[i];
                }
                else
                {
                    output += "*";
                }
            }
            else
            {
                if (i == 0)
                {
                    output += array1[i];
                }
                else
                {
                    output += "*";
                }
            }              
        }
        output += "@";
        for (int i = 0; i < array2.Length; i++) output += "*";
        for (int i = 1; i < newsplit.Length; i++) output += "." + newsplit[i];

        return output;
    }
Share:
19,351

Related videos on Youtube

Sara Khan
Author by

Sara Khan

Updated on September 15, 2022

Comments

  • Sara Khan
    Sara Khan over 1 year

    i have an issue, i have to apply masking/hiding part of email address in c#. example

    [email protected]==> jh**[email protected]
    [email protected]==> bi****[email protected]
    [email protected]==>br*******[email protected]
    

    i have this code but its giving exception for some emails. "Index was outside the bounds of the array."

    for (int i = 0; i < eml.Length; i++)
    {
     int j = i == (eml.Length - 1) ? 0 : 1;
     cc = eml[i].ToString();
     if (i <= 1)
     {
      dispeml += cc;
     }
     else 
     if (eml[i + (j + k)].ToString() == "@")
     {
      dispeml += cc;
      k = 0;
      fl = 1;
     }
     else 
     if (eml[i + j].ToString() == "@")
     {
      dispeml += cc;
      fl = 1;
     }
     else 
     if (fl == 1)
     {
      dispeml += cc;
     }
     else
     {
      dispeml += "*";
     }
    }
    
    • Steve
      Steve
      Why don't you start your debugger and look what happen in this code? You are in the best position to discover the fault. Just put a breakpoint at the start of this code and run the debugger.
    • Richard
      Richard
      "giving exception for some emails": I suppose we could guess what they are. But it would be better to include the details of which emails are failing with which exception and what point in the code.
  • Saad Farooq
    Saad Farooq about 8 years
    Great Solution. Thank you for the Regex! :)
  • Djorge
    Djorge almost 7 years
    How would I make this affect the domain of the e-mail address as well?
  • fubo
    fubo almost 7 years
    @Djorge that's a bit tricky because the domain technically cold be @foo, @foo.bar.com or @192.168.1.1 beside the trivial case @foo.com
  • Djorge
    Djorge almost 7 years
    I ended up adding |(?<=@[\w]{1})[\w-_\+%]*(?=\.) to the end of your regex to get what I wanted, doesn't handle @foo though.
  • needfulthing
    needfulthing about 5 years
    @Djorge If you remove the at sign in your addition, you can also match multiple domain parts. The whole expression would be (?<=[\w]{1})[\w-\._\+%]*(?=[\w]{1}@)|(?<=[\w]{1})[\w-_\+%]*(‌​?=\.) then