Protecting Sensitive Strings: Redaction vs. Masking
When handling sensitive information like passwords, API keys, or personal data, it’s important to protect this data when displaying or logging it. Two common techniques for this are redaction and masking.
- Redaction shortens the string by showing only the start and end, replacing the middle with a placeholder such as
"..."
. This gives a clear but limited preview of the data. - Masking hides part of the string by replacing the middle characters with a repeated symbol (like
*
), keeping the original length intact and showing only limited characters at the start and end.
Choosing between redaction and masking depends on your needs: whether you want to reduce visible length for compact display (redaction), or maintain length for format consistency while hiding data (masking).
Redaction hides sensitive parts of a string by keeping only a visible prefix and suffix and inserting a customizable placeholder (such as "..."
) in the middle. If the string is too short, it returns just the placeholder to avoid revealing data.
Key points:
- Shows a prefix and suffix of the string, with a redaction string in between.
- If the string is too short, it returns just the redaction string to avoid exposing sensitive data.
- Supports customizable redaction strings (e.g.,
"..."
,"###"
, or emojis).
Example Implementation:
public static string Redact(string token, int prefixLength = 4, int suffixLength = 4, string redactionString = "...")
{
if (string.IsNullOrWhiteSpace(token)) return "[Token is null or empty]";
if (prefixLength < 0 || suffixLength < 0) return "[Invalid prefix or suffix length]";
if (string.IsNullOrEmpty(redactionString)) redactionString = "...";
int tokenLength = token.Length;
int minLengthForFullRedaction = prefixLength + suffixLength + redactionString.Length;
if (tokenLength >= minLengthForFullRedaction)
{
string prefix = token.Substring(0, prefixLength);
string suffix = token.Substring(tokenLength - suffixLength);
return $"{prefix}{redactionString}{suffix}";
}
int minLengthForPrefixOnly = prefixLength + redactionString.Length;
if (tokenLength >= minLengthForPrefixOnly)
{
string prefix = token.Substring(0, prefixLength);
return $"{prefix}{redactionString}";
}
return redactionString;
}
Use Case:
Useful for logs or UI where a brief summary of sensitive data is needed without showing the entire value.
Comments