no

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 i...

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();
 }
}

Related

java-library 1087461030893585294

Post a Comment Default Comments

item