Saturday 26 November 2022

Create Rest APT to Encrypt and Decrypt message using AES/CBC/PKCS5PADDING algorithm

Project Structure



Calling Response from Postman tool





------------------------------------------- Controller ---------------------------------------------
package com.ramsis.encrypt.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ramsis.encrypt.util.EncryptionDecryption;
import com.ramsis.encrypt.dto.POJO;

@RestController
public class Controller {
   
@Autowired
EncryptionDecryption ecndnc;

@Value("${EncDncKey}")
String publickey;

@CrossOrigin(origins = "*")
@PostMapping("/Ngdecrypt")
public POJO NGdecrypt(@RequestBody POJO pojo) throws Exception {

String msg = pojo.getMessage();
String enckey = pojo.getKeys();
String decryptString = null;
// String publickey = "3K4G2pb4dl8M/7YaOrGiPA=="; // 128 bit key
try {
if (!enckey.equalsIgnoreCase(publickey)) {
System.out.println("You are not Authorised.");
pojo.setMessage("Not Authorised.");
System.out.println(pojo.getMessage());
return pojo;
}

decryptString = ecndnc.decrypt(publickey, null, msg);
pojo.setMessage(decryptString);
} catch (Exception ex) {
ex.getMessage();
}

return pojo;
}

@CrossOrigin(origins = "*")
@PostMapping("/Ngencrypt")
public POJO Ngencrypt(@RequestBody POJO pojo) throws Exception {

String msg = pojo.getMessage();
String enckey = pojo.getKeys();
String encryptString = null;
try {
if (!enckey.equalsIgnoreCase(publickey)) {
System.out.println("You are not Authorised.");
pojo.setMessage("Not Authorised.");
return pojo;
}
encryptString = ecndnc.encrypt(publickey, null, msg);
pojo.setMessage(encryptString);
//System.out.println(encryptString);
} catch (Exception ex) {
ex.getMessage();
}
return pojo;
}
}

----------------------------------------EncryptionDecryption----------------------------------------

package com.ramsis.encrypt.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

@Component
public class EncryptionDecryption {

public static String encrypt(String key, String initVector, String value) {
byte[] encrypted =null;
try {
initVector = key.substring(0, 16); // 16 bytes IV
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

   encrypted = cipher.doFinal(value.getBytes());
System.out.println("encrypted string: " + Base64.encodeBase64String(encrypted));
} catch (Exception ex) {
ex.printStackTrace();
}
return Base64.encodeBase64String(encrypted);
}

public static String decrypt(String key, String initVector, String encrypted) {
byte[] original =null;
try {
initVector = key.substring(0, 16);
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
   original = cipher.doFinal(Base64.decodeBase64(encrypted));
} catch (Exception ex) {
ex.printStackTrace();
}
return new String(original);
}

}

------------------------------------------------ CallAPI ----------------------------------------------
package com.ramsis.encrypt.callApi;

import org.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class CallAPI {

public void restAPITest(String url, String message) {

String key = "3K4G2pb4dl8M/7YaOrGiPA==";
try {
RestTemplate restTemplate = new RestTemplate();
JSONObject personJsonObject = new JSONObject();
personJsonObject.put("keys", key);
personJsonObject.put("message", message);

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<String> entityHttp = new HttpEntity<String>(personJsonObject.toString(), headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entityHttp, String.class);
/*
* String answer = restTemplate.postForObject(url, entity, String.class);
* System.out.println(answer);
*/
if (response.getStatusCodeValue() == 200) {
System.out.println(response.getBody());
}

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

public static void main(String args[]) throws Exception {
CallAPI call = new CallAPI();
//call.restAPITest("http://localhost:8080/Ngencrypt", "ramsis-code");
call.restAPITest("http://localhost:8080/Ngdecrypt", "TaZydiy5PHtA4ME8744bOA==");

}
}

1 comment:

  1. Thank you sir for supporting error solving blog

    ReplyDelete