How to encode and decode a JSON encrypted string in java
Tech-Today

How to encode and decode a JSON encrypted string in java


This tutorial requires the use of apache commons and jackson libraries. For example I have a highly confidential string and I want to send it over the net, of course normally I want to encrypt it. And one of the method we can send this encrypted string over the net is by JSON format.

Here's how I did it (to make things easier I posted my code):


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>encryptionDemo</groupId>
<artifactId>encryptionDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>

<dependencies>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.0.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.0.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.0.4</version>
</dependency>
</dependencies>
</project>

JSONUtils, use to encode and decode a string:

package com.ipiel.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONUtils {
static ObjectMapper mapper = new ObjectMapper();

public static String toJSON(Object o) {
String result = "";
if (o != null) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
mapper.writeValue(out, o);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
result = out.toString("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return result;
}

public static T parseJSON(String jsonString, Class beanClass)
throws JsonParseException, JsonMappingException, IOException {
return mapper.readValue(jsonString, beanClass);
}
}

And finally, the class that encrypts and decrypts the string:

package com.ipiel.utils;

import java.beans.IntrospectionException;
import java.io.IOException;
import java.security.InvalidKeyException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.commons.codec.binary.Base64;

import com.ipiel.models.Address;
import com.ipiel.models.Student;

public class IpielContextParser {
Cipher cipher;
SecretKey myDesKey;

public IpielContextParser(String secretkey) {
try {
DESKeySpec dks = new DESKeySpec(secretkey.getBytes());
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
myDesKey = skf.generateSecret(dks);
cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
} catch (Exception e) {
e.printStackTrace();
}
}

public String encodeBeanToString(Student student)
throws IllegalBlockSizeException, BadPaddingException,
InvalidKeyException {
String result = null;
String jsonString = JSONUtils.toJSON(student);
byte[] text = jsonString.getBytes();
cipher.init(Cipher.ENCRYPT_MODE, myDesKey);
byte[] textEncrypted = cipher.doFinal(text);
result = Base64.encodeBase64String(textEncrypted);

return result;
}

public Student decodeStringToBean(String param) throws IOException,
InvalidKeyException, IllegalBlockSizeException,
BadPaddingException, IntrospectionException {
byte[] decodedBytes = Base64.decodeBase64(param);
cipher.init(Cipher.DECRYPT_MODE, myDesKey);
byte[] textDecrypted = cipher.doFinal(decodedBytes);

return JSONUtils.parseJSON(new String(textDecrypted), Student.class);
}

private void test() {
Address address = new Address();
address.setCountry("PH");
address.setZip("4030");

Student student = new Student();
student.setAddress(address);
student.setName("Ipiel");
student.setAge(27);

try {
String encoded = encodeBeanToString(student);
System.out.println("encoded: " + encoded);
Student decoded = decodeStringToBean(encoded);
System.out.println("decoded: " + decoded);
} catch (Exception e) {

}
}

public static void main(String args[]) {
new IpielContextParser("yxvuicidunccxnxzquidxstraitsdxsunmaitrxadxtruityharmunix").test();
}
}




- Social Login Using Rest Fb
This is an implementation tutorial on how we can use REST FB to enable facebook social login on our web application. Basically, it's a project created from javaee7-war template. To run this app you need to set up a Facebook application with callback...

- Encode Image And Display In Html
To encode an image file(eg. png, jpg, gif) we will need the apache commons-codec library. To avoid it in a maven project: <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.11</version>...

- How To Encrypt And Decrypt An Object In And From A File In Java
There are times when we need to write something on a file, but doesn't want it to be readable as a plain text. In this case we can use any type of encryption mechanism, but what if we want to decrypt the encrypted file back and read its contents....

- How To Enable Jersey Rest Api In A Maven Web Project
This tutorial assumes that you already know how to create a maven project in eclipse. Steps: 1.) Create a new maven web project. (this assumes that you have maven plugin installed in your eclipse). 2.) In your META-INF/web.xml file make sure that you...

- How To Add Pmd Reporting To Maven
Before proceeding to this exercise, you may want to try my tutorial on how to setup a maven project to eclipse: http://czetsuya-tech.blogspot.com/2012/04/how-to-create-modularized-maven-project.html. Assuming you have follow the tutorial above, you should...



Tech-Today








.