.NET by Patrik

Redaction — Showing Partial Data Safely

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.

redaction
security
string
privacy
data-protection

Comments