Skip to content

Instantly share code, notes, and snippets.

@mrpmorris
Created June 21, 2022 15:54
Show Gist options
  • Save mrpmorris/c0b217888bb3a98d3420fb0fd6b5689a to your computer and use it in GitHub Desktop.
Save mrpmorris/c0b217888bb3a98d3420fb0fd6b5689a to your computer and use it in GitHub Desktop.
ObscureEmailAddress
public static class StringHelper
{
public const byte DefaultUnobscuredLength = 3;
public enum Keep { Start, End };
public static string? ObscureEmailAddress(string? value)
{
if (string.IsNullOrEmpty(value))
return value;
string?[] parts = value.Split('@');
Keep keep = Keep.Start;
for(int i = 0; i < parts.Length; i++)
{
parts[i] = Obscure(parts[i], keep, 3);
keep = Keep.End;
}
return String.Join('@', parts);
}
public static string? Obscure(string? value, Keep keep, int unobscuredLength = DefaultUnobscuredLength)
{
if (string.IsNullOrEmpty(value))
return value;
if (unobscuredLength < 0)
throw new ArgumentOutOfRangeException(message: "Must be at least 0", paramName: nameof(unobscuredLength));
// Ensure we obscure at least half of the string, and reveal at most DefaultUnobscuredLength (3) chars.
unobscuredLength = Math.Min(unobscuredLength, value.Length / 2);
return keep switch
{
Keep.Start => value[0..unobscuredLength] + new string('*', value.Length - unobscuredLength),
_ => new string('*', value.Length - unobscuredLength) + value[^unobscuredLength..]
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment