Successfully added
.NET
by Patrik
Masking — Obscuring Data While Preserving Length
Summary:
Masking replaces the middle part of a string with repeated mask characters (like *
), preserving the string’s total length and showing only a visible prefix and suffix. If the string is too short, it masks the entire string. The mask character can be customized.
Key points:
- Shows a defined number of characters at the start and end of the string.
- Replaces the middle characters with a masking character (default
*
). - Supports custom mask characters.
- If the string is too short to be partially masked, it masks the entire string.
Example Implementation:
public static string Mask(string input, int prefixLength = 4, int suffixLength = 4, char maskCharacter = '*')
{
if (string.IsNullOrWhiteSpace(input)) return new string(maskCharacter, 3);
if (prefixLength < 0 || suffixLength < 0)
throw new ArgumentOutOfRangeException("Prefix and suffix lengths cannot be negative.");
int inputLength = input.Length;
if (prefixLength + suffixLength >= inputLength)
{
return new string(maskCharacter, inputLength);
}
string prefix = input.Substring(0, prefixLength);
string suffix = input.Substring(inputLength - suffixLength);
string maskedPart = new string(maskCharacter, inputLength - prefixLength - suffixLength);
return prefix + maskedPart + suffix;
}
Use Case:
Ideal when you need to display partial information while maintaining the same length, such as masking credit card numbers or tokens in a UI.
masking
obfuscation
string
security
privacy
Referenced in:
Comments