Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private static readonly int CreditCardLengthMin = 13;
- private static readonly int CreditCardLengthMax = 19;
- public static string OmitSensitiveData(string str)
- {
- var start = -1; // start index of the card number
- var count = 0; // number of characters in the card number
- var nextSeparator = -1;
- StringBuilder builder = new StringBuilder(str);
- for (int i = 0; i < str.Length; i++)
- {
- char c = builder[i];
- bool expectingSeparator = nextSeparator == i;
- if (expectingSeparator) nextSeparator += 5;
- if (char.IsNumber(c))
- {
- if (start == -1) {
- start = i;
- nextSeparator = i + 4;
- }
- count++; // increment number count
- if (count == CreditCardLengthMin) // have the minimum amount of characters
- {
- // reached the minimum size of a credit card number
- // we will mask it up to here. if it has more then it will be masked
- // as its being parsed
- OmitNumbers(builder, start, i + 1);
- continue;
- } else if (count > CreditCardLengthMin) // have more than the minimum
- {
- // omit the number
- OmitNumber(builder, i);
- if (count >= CreditCardLengthMax)
- {
- // we've hit the end of the line
- // no break so start and count will be reset
- } else continue; // haven't reached the maximum yet
- } else continue; // haven't hit a min yet, don't reset
- } else if (start != -1 // has started
- && (c.Equals(' ') || c.Equals('-')) // is acceptable character
- && expectingSeparator)
- {
- continue; // acceptable
- }
- // non number or acceptable character, reset
- start = -1;
- count = 0;
- nextSeparator = -1;
- }
- return builder.ToString();
- }
- private static void OmitNumber(StringBuilder builder, int index)
- {
- if (char.IsNumber(builder[index])) builder[index] = 'X';
- }
- private static void OmitNumbers(StringBuilder builder, int start, int end)
- {
- for (int i = start; i < end; i++)
- {
- OmitNumber(builder, i);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment