Mask value for the selected key in JSON
I have a JSON request and response, I want to print the JSON to the log, but there are some protected fields that I want to avoid to print in the log, I am trying to hide the field keys: Example:
before disguising:
{"username":"user1","password":"123456","country":"US","creditCardNumber":"1283-1238-0458-3458"}
after disguise
{"username":"user1","password":"XXXXXX","country":"US","creditCardNumber":"XXXXXX"}
I am using java Gson lib please help me to do this
EDIT
I want to pass keys dynamically, so in the function a
I want to hide these fields, but there are b
different fields in the function .
source to share
I think you should exclude these fields from the log. Below is a simple example using annotations Gson
and @Expose
.
public static void main(String[] args) throws IOException {
String json = "{\"username\":\"user1\",\"password\":\"123456\",\"country\":\"US\",\"creditCardNumber\":\"1283-1238-0458-3458\"}";
Gson gson = new Gson();
User user = gson.fromJson(json, User.class);
System.out.println(gson.toJson(user));
Gson gsonExpose = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
System.out.println(gsonExpose.toJson(user));
}
public class User {
@Expose
private String username;
private String password;
@Expose
private String country;
private String creditCardNumber;
}
The output will be:
{"username":"user1","password":"123456","country":"US","creditCardNumber":"1283-1238-0458-3458"}
{"username":"user1","country":"US"}
Another solution using Reflection:
public static void main(String[] args) throws IOException {
String json = "{\"username\":\"user1\",\"password\":\"123456\",\"country\":\"US\",\"creditCardNumber\":\"1283-1238-0458-3458\"}";
Gson gson = new Gson();
User user = gson.fromJson(json, User.class);
List<String> fieldNames = Arrays.asList("password", "creditCardNumber");
System.out.println(mask(user, fieldNames, "XXXXXXX"));
}
public static String mask(Object object, List<String> fieldNames, String mask) {
Field[] fields = object.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
if (fieldNames.contains(fields[i].getName())) {
try {
fields[i].setAccessible(true);
if (fields[i].get(object) != null) {
fields[i].set(object, mask);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Gson gson = new Gson();
return gson.toJson(object);
}
source to share
Here is a link to cover all type of sensitive information such as (SSN, credit card, DOB, etc.) to mask with an example. Even this will help you cover other cases like masking on log4j, java objects, JSON and web pages.
Log4j2: how to mask logs private / confidential / SPI information
How to mask JSON sensitive / private information in logs: JAVA
source to share