user3174976
user3174976

Reputation: 351

How to sanitize/hide sensitive data in C#

For logging transactions purpose, I need to tell whether users provide the necessary fields/information or not. If yes, I will replace the real information with *. If no, I will make this request as failed one, with returning "false" value.

The following are the data definition class and method.

public class CreditCard
{
 public string brand { get; set; }
 public string billingphone { get; set; }
}   

class Program
{
   static void Main(string[] args)
   {
    CreditCard creditcard =new CreditCard(){brand="VISA", billingphone="777-111-2222"};
    bool IsVerified= SanitizePaymnetData(creditcard);        
   }

  private bool SanitizePaymnetData(ref CreditCard creditcard)
    {
        bool isDataSanitized = true;

        if(!String.IsNullOrEmpty(creditcard.brand))
        {
           creditcard.brand ="*";               
        }
        else
        {
            isDataSanitized = false;
        }

        if (!String.IsNullOrEmpty(creditcard.billingphone))
        {
            creditcard.billing_phone = "*";
        }
        else
        {
            isDataSanitized = false;
        }

        return isDataSanitized;
    } 
}

The "SanitizePaymentData" method looks kind of ugly. Is there any way to make it more clean/neat?

Upvotes: 1

Views: 4452

Answers (1)

Jedediah
Jedediah

Reputation: 1944

The main issue I see here is potentially one of maintainability. As you add fields to CreditCard, you'll have to add additional checks in SantitzePaymentData(). If other developers later work on this, they may not be aware of that requirement, or you might forget about later on down the road, and sensitive information would start showing up in your log. Since this wouldn't generate an exception or compilation error, it could be some time before you notice this has happened.

I don't know if this is a real project, or just something you're using to learn, but another issue arises when you decide to add another payment method, like a wire transfer. You'll then have to create another SanitizePaymentData() function that works on the new payment class, but it will have essentially duplicate code from your original method. This duplicates work, violates the DRY principal, and creates clutter in your project.

In my opinion, a much cleaner approach would be to use attributes in your class that mark sensitive fields as needing to be sanitized, and then have your logger respond appropriately.

public class CreditCard
{
    [SanitizeInLog]
    public string Brand {get; set;}

    [SanitizeInLog]
    public string BillingPhone {get; set;}
}

Now, your logging method/class can simply check to see if those attributes exist on a field, and switch them out for a "*" or whatever else.

Upvotes: 7

Related Questions