Masking Credit Card number in Java

Sometimes we need to mask crucial information like Credit Card Numbers, CVV numbers etc before storing  or logging the information. This example mask Credit Card Number (Except last 4 Digit) from a Text which contains information along with Credit Card Number.

The following example demonstrates how we can easily mask the credit card with Matcher and Pattern Classes. This Sample Code uses Matcher and Pattern.
Pattern Used in this sample is not optimized for Credit Card Numbers, this pattern will get any numerical numbers in the String Content.  Based on the Credit Card Type a more efficient and Strict RegEx can be used to mask the Credit Card.
 

/**Mask the Credit card number but last four digit value **/
        
         Pattern PATTERN = Pattern.compile("[0-9]+");

        String message = content;
        Matcher matcher = PATTERN.matcher(message);
        String maskingChar = "*";
        StringBuilder finalMask = new StringBuilder(maskingChar);

        while (matcher.find()) {
            String group = matcher.group();
            int groupLen = group.length();

            if(groupLen>4){
                for(int i=0; i<=group.length()-4; i++){
                    finalMask.append(maskingChar);
                }
                finalMask.append(group.substring(groupLen-4));
            }
            message = message.replace(group, finalMask);
        }
        return message;
    
If we pass Strings like  This is my Credit Card 11001100032000420035 it will return
This is my Credit Card ******************0035.

Comments

  1. Why only mask all but 4 digits

    ReplyDelete
  2. Thank this is what i have been looking ofr

    ReplyDelete
  3. Thanks a lot for this example. It helped me to achieve my task.

    ReplyDelete
    Replies
    1. Happy that this post helped you. Please also find the github code for this here
      https://github.com/siddharthagit/javaexpcode/blob/master/src/javaexp/blog/CreditcardMask.java

      Delete
  4. Your code implementation and explanation showcase a keen understanding of data protection. The meticulous steps you outline ensure sensitive information remains confidential. Understanding Mitiga Ting A vital resource for developers dedicated to safeguarding user.

    ReplyDelete

Post a Comment

Popular posts from this blog

Converting Java Map to String

Invoking EJB deployed on a remote machine

Difference between volatile and synchronized