Tag Archives: Google GSON

How to Mask JSON Confidential/Personal Information in logs :JAVA

Here you will see all steps to mask confidential/ information like credit card, CVV, Exp date,  SSN, password etc. So that it will print in mask form as ****** so that unauthorize use will not misuse of others information.

Here using Google GSON and GsonBuilder converting Java object to JSON and again converting JSON to Java Object.

By using Java refelection api’s replacing SPI fields data with *******.

Input JSON File AccountDetail


{
  "firstName": "Saurabh",
  "lastName": "Gupta",
  "address": {
    "addressLine1": "Noida City Center",
    "city": "Noida",
    "state": "UP",
    "pincode": "India",
    "country": "20310"
  },
  "creditCardDetail": {
    "cardNumber": "1234567890123456",
    "cvv": "123",
    "expDate": "12/90"
  }
}

 

Code to Mask JSON

package com.mask.json;

import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class MaskJSONTest {
	static Set fieldSet = new HashSet();
	static List fieldNames = Arrays.asList("cardNumber", "cvv", "expDate");

	public static void main(String[] args) throws IOException {
		StringBuilder contentBuilder = new StringBuilder();
		try (Stream stream = Files.lines(
				Paths.get(
						"D:\\Saurabh Gupta\\Workspace\\JavaTestExamples\\src\\main\\resources\\AccountDetail.json"),
				StandardCharsets.UTF_8)) {
			stream.forEach(s -> contentBuilder.append(s).append("\n"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		//Create GSON object
		//apply NullSearialization and Pretty formatting by GSON Builder
		Gson gson = getJsonBuilder().create();
		AccountDetail accounDetail = gson.fromJson(contentBuilder.toString(), AccountDetail.class);
		mask(accounDetail);
		System.out.println(gson.toJson(accounDetail));
	}
	public static GsonBuilder getJsonBuilder()
	{
		GsonBuilder builder = new GsonBuilder();

		// Setting for formatted output and serialize null value
		builder.setPrettyPrinting().serializeNulls();

		return builder;
	}

	public static void mask(Object object) {
		try {
			Field[] fields = object.getClass().getDeclaredFields();
			Object value = null;
			for (int i = 0; i <span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>&lt; fields.length; i++) {
				fields[i].setAccessible(true);
				value = fields[i].get(object);
				if (value != null &amp;&amp; fieldSet.add(fields[i].getName())) {
					if (fields[i].getType().isArray()
							|| fields[i].getType().getCanonicalName().startsWith(&quot;com.mask.json&quot;)) {
						mask(value);
					} else {
						if (fieldNames.contains(fields[i].getName()) &amp;&amp; fields[i].get(object) != null) {
							fields[i].set(object, replaceDigits((String) fields[i].get(object)));
						}
					}
				}

			}
		} catch (IllegalAccessException ex) {
			ex.printStackTrace();
		}
	}

	private static String replaceDigits(String text) {
		StringBuffer buffer = new StringBuffer(text.length());
		Pattern pattern = Pattern.compile(&quot;\\d&quot;);
		Matcher matcher = pattern.matcher(text);
		while (matcher.find()) {
			matcher.appendReplacement(buffer, &quot;X&quot;);
		}
		return buffer.toString();
	}

}

Model Classes


package com.mask.json;

public class AccountDetail {
private String firstName;
private String lastName;
private AddressDetail address;
private CreditCardDetail creditCardDetail;
public AccountDetail(String firstName, String lastName, AddressDetail address, CreditCardDetail creditCardDetail) {
	super();
	this.firstName = firstName;
	this.lastName = lastName;
	this.address = address;
	this.creditCardDetail = creditCardDetail;
}
public String getFirstName() {
	return firstName;
}
public void setFirstName(String firstName) {
	this.firstName = firstName;
}
public String getLastName() {
	return lastName;
}
public void setLastName(String lastName) {
	this.lastName = lastName;
}
public AddressDetail getAddress() {
	return address;
}
public void setAddress(AddressDetail address) {
	this.address = address;
}
public CreditCardDetail getCreditCardDetail() {
	return creditCardDetail;
}
public void setCreditCardDetail(CreditCardDetail creditCardDetail) {
	this.creditCardDetail = creditCardDetail;
}

}


package com.mask.json;

public class AddressDetail {

private String addressLine1;
private String city;
private String state;
private String pincode;
private String country;

public AddressDetail(String addressLine1, String city, String state, String pincode, String country) {
	super();
	this.addressLine1 = addressLine1;
	this.city = city;
	this.state = state;
	this.pincode = pincode;
	this.country = country;
}
public String getAddressLine1() {
	return addressLine1;
}
public void setAddressLine1(String addressLine1) {
	this.addressLine1 = addressLine1;
}
public String getCity() {
	return city;
}
public void setCity(String city) {
	this.city = city;
}
public String getState() {
	return state;
}
public void setState(String state) {
	this.state = state;
}
public String getPincode() {
	return pincode;
}
public void setPincode(String pincode) {
	this.pincode = pincode;
}
public String getCountry() {
	return country;
}
public void setCountry(String country) {
	this.country = country;
}

}

package com.mask.json;

public class CreditCardDetail{
private String cardNumber;
private String cvv;
private String expDate;

public CreditCardDetail(String cardNumber, String cvv, String expDate) {
	super();
	this.cardNumber = cardNumber;
	this.cvv = cvv;
	this.expDate = expDate;
}

public String getCardNumber() {
	return cardNumber;
}
public void setCardNumber(String cardNumber) {
	this.cardNumber = cardNumber;
}
public String getCvv() {
	return cvv;
}
public void setCvv(String cvv) {
	this.cvv = cvv;
}
public String getExpDate() {
	return expDate;
}
public void setExpDate(String expDate) {
	this.expDate = expDate;
}

}

Output Masked JSON :

{
“firstName”: “Saurabh”,
“lastName”: “Gupta”,
“address”: {
“addressLine1”: “Noida City Center”,
“city”: “Noida”,
“state”: “UP”,
“pincode”: “India”,
“country”: “20310”
},
“creditCardDetail”: {
“cardNumber”: “XXXXXXXXXXXXXXXX”,
“cvv”: “XXX”,
“expDate”: “XX/XX”
}
}

Related Posts

Below are some more masking ways for different type of data like XML, JSON and printing objects before logging , sending to page or transferring over network.

Log4j2: How to Mask Logs Personal/Confidential/SPI Information

How to MASK XML Confidential/Personal Data : JAVA

How to mask JAVA Object confidential/personal information in logs while Printing

Advertisements