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.
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.
Why only mask all but 4 digits
ReplyDeleteThank this is what i have been looking ofr
ReplyDeleteThanks a lot for this example. It helped me to achieve my task.
ReplyDeleteHappy that this post helped you. Please also find the github code for this here
Deletehttps://github.com/siddharthagit/javaexpcode/blob/master/src/javaexp/blog/CreditcardMask.java
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