fr1kin

Sensitive credit card number omitter

Jul 4th, 2017
419
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.96 KB | None | 0 0
  1. private static readonly int CreditCardLengthMin = 13;
  2. private static readonly int CreditCardLengthMax = 19;
  3.  
  4. public static string OmitSensitiveData(string str)
  5. {
  6.     var start = -1; // start index of the card number
  7.     var count = 0; // number of characters in the card number
  8.     var nextSeparator = -1;
  9.  
  10.     StringBuilder builder = new StringBuilder(str);
  11.     for (int i = 0; i < str.Length; i++)
  12.     {
  13.         char c = builder[i];
  14.         bool expectingSeparator = nextSeparator == i;
  15.         if (expectingSeparator) nextSeparator += 5;
  16.         if (char.IsNumber(c))
  17.         {
  18.             if (start == -1) {
  19.                 start = i;
  20.                 nextSeparator = i + 4;
  21.             }
  22.             count++;                                    // increment number count
  23.             if (count == CreditCardLengthMin) // have the minimum amount of characters
  24.             {
  25.                 // reached the minimum size of a credit card number
  26.                 // we will mask it up to here. if it has more then it will be masked
  27.                 // as its being parsed
  28.                 OmitNumbers(builder, start, i + 1);
  29.                 continue;
  30.             } else if (count > CreditCardLengthMin) // have more than the minimum
  31.             {
  32.                 // omit the number
  33.                 OmitNumber(builder, i);
  34.                 if (count >= CreditCardLengthMax)
  35.                 {
  36.                     // we've hit the end of the line
  37.                     // no break so start and count will be reset
  38.                 } else continue; // haven't reached the maximum yet
  39.             } else continue; // haven't hit a min yet, don't reset
  40.         } else if (start != -1                           // has started
  41.             && (c.Equals(' ') || c.Equals('-'))         // is acceptable character
  42.             && expectingSeparator)
  43.         {
  44.             continue; // acceptable
  45.         }
  46.         // non number or acceptable character, reset
  47.         start = -1;
  48.         count = 0;
  49.         nextSeparator = -1;
  50.     }
  51.     return builder.ToString();
  52. }
  53.  
  54. private static void OmitNumber(StringBuilder builder, int index)
  55. {
  56.     if (char.IsNumber(builder[index])) builder[index] = 'X';
  57. }
  58.  
  59. private static void OmitNumbers(StringBuilder builder, int start, int end)
  60. {
  61.     for (int i = start; i < end; i++)
  62.     {
  63.         OmitNumber(builder, i);
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment