Search code examples
c#asp.netquery-stringnamevaluecollection

mask query dynamic query string value


I am building a wrapper to process payments. We want to log requests, but don't want to store sensitive credit card data. A query string will be passed similar to what is below

amount=100.00&expMonth=01&expYear=14&cardnumber=4111111111111111

I want to mask the first 12 digits of the credit card number with X values. However, the cardnumber key will not always be in the same spot.

My first leaning is to create a NameValueCollection and check for the key and do a string.format("XXXX-XXXX-XXXX-{0}", substring of the value

var qs = HttpUtility.ParseQueryString(request);
foreach (string key in qs)
{
    if (key == "creditcard")
    {

    }
}

Can someone point me in the right direction?

I need to save the string in the same format with just the credit card number masked.


Solution

  • This works great, there may be a more elegant solution though.

    var maskedRequest = "";
    var qs = HttpUtility.ParseQueryString(request);
    foreach (string item in qs.AllKeys)
    {
       if (item != "cardnumber")
       {
           maskedRequest = maskedRequest + item + "=" + qs.Get(item) + "&";
       }
       else
       {
           maskedRequest = maskedRequest + item + "=" + string.Format("XXXX-XXXX-XXXX-{0}", qs.Get(item).Substring(12, 4)) + "&";
        }
    }
    
    maskedRequest = maskedRequest.Remove(maskedRequest.Length - 1)