Java Encryption v2
Login

Java Encryption v2

Encryption Class

Create a new Encryption.java class and paste in the following Java code

import java.util.Base64;
import javax.crypto.Cipher;
import java.security.MessageDigest;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import javax.crypto.spec.IvParameterSpec;

public class Encryption {

    private String ivKey;
    private String secretKey;

    public Encryption(String ivKey, String secretKey) {
        this.ivKey = ivKey;
        this.secretKey = secretKey;
    }

    /**
     * encrypt - a function to encrypt your string using AES 128 it encrypts to
     * AES 128 if we specify no padding to be done
     *
     * @param plainText String
     * @return String
     * @throws Exception
     */
    public String encrypt(String plainText) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hashedIV = digest.digest(this.ivKey.getBytes(StandardCharsets.UTF_8));
        byte[] hashedSecret = digest.digest(this.secretKey.getBytes(StandardCharsets.UTF_8));

        IvParameterSpec IV = new IvParameterSpec(
                bytesToHex(hashedIV).substring(0, 16).getBytes()
        );

        SecretKeySpec secret = new SecretKeySpec(
                bytesToHex(hashedSecret).substring(0, 32).getBytes(),
                "AES"
        );

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret, IV);
        byte[] encrypted = cipher.doFinal(plainText.getBytes());

        String params = Base64.getEncoder().encodeToString(encrypted);
        return Base64.getEncoder().encodeToString(params.getBytes());
    }

    /**
     * bytesToHex - a function to convert encrypted byte to a hexadecimal String
     *
     * @param data byte[]
     * @return string String
     */
    public static String bytesToHex(byte[] data) {
        if (data == null) {
            return null;
        }

        int len = data.length;
        String string = "";
        for (int i = 0; i < len; i++) {
            if ((data[i] & 0xFF) < 16) {
                string = string + "0" + java.lang.Integer.toHexString(data[i] & 0xFF);
            } else {
                string = string + java.lang.Integer.toHexString(data[i] & 0xFF);
            }
        }
        return string;
    }

}

Encryption Class Usage (Springboot)

For this example, we will use the Spring Boot framework for a realistic illustration. Follow the steps below to import the application. A more comprehensive guide to creating a Spring Boot app with the web route can be found here.

Step 1: Create a maven project.

Step 2: Open the spring boot app and copy the java code below.

import org.springframework.web.bind.annotation.*;
import com.google.gson.Gson;


@RestController
public class CheckoutEncryption {
    @PostMapping("/checkout-encryption")
    @ResponseBody
    public static CheckoutResponse encryption(@RequestBody Payload payload){
        Gson gson = new Gson();

        String access_key = "<YOUR_ACCESS_KEY>";
        String iv_key = "<YOUR_IV_KEY>";
        String secret_key = "<YOUR_SECRET_KEY>";

        Encryption encryption = new Encryption(iv_key, secret_key);
        try {
            String json = gson.toJson(payload);
            String params = encryption.encrypt(json);
            return new CheckoutResponse(params, access_key, payload.getCountryCode());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

//Payload model class
class Payload {
    private String merchantTransactionID;
    private String customerFirstName;
    private String customerLastName;
    private String MSISDN;
    private String customerEmail;
    private String requestAmount;
    private String currencyCode;
    private String accountNumber;
    private String serviceCode;
    private String dueDate;
    private String requestDescription;
    private String countryCode;
    private String languageCode;
    private String payerClientCode;
    private String successRedirectUrl;
    private String failRedirectUrl;
    private String pendingRedirectUrl;
    private String paymentWebhookUrl;

    public Payload(String merchantTransactionID, String customerFirstName, String customerLastName, String MSISDN, String customerEmail, String requestAmount, String currencyCode, String accountNumber, String serviceCode, String dueDate, String requestDescription, String countryCode, String languageCode, String payerClientCode, String successRedirectUrl, String failRedirectUrl, String pendingRedirectUrl, String paymentWebhookUrl) {
        this.merchantTransactionID = merchantTransactionID;
        this.customerFirstName = customerFirstName;
        this.customerLastName = customerLastName;
        this.MSISDN = MSISDN;
        this.customerEmail = customerEmail;
        this.requestAmount = requestAmount;
        this.currencyCode = currencyCode;
        this.accountNumber = accountNumber;
        this.serviceCode = serviceCode;
        this.dueDate = dueDate;
        this.requestDescription = requestDescription;
        this.countryCode = countryCode;
        this.languageCode = languageCode;
        this.payerClientCode = payerClientCode;
        this.successRedirectUrl = successRedirectUrl;
        this.failRedirectUrl = failRedirectUrl;
        this.pendingRedirectUrl = pendingRedirectUrl;
        this.paymentWebhookUrl = paymentWebhookUrl;
    }

    public String getCountryCode() {
        return countryCode;
    }
}

//Checkout Response class
class CheckoutResponse {
    private String params;
    private String accessKey;
    private String countryCode;

    public CheckoutResponse(String params, String accessKey, String countryCode) {
        this.params = params;
        this.accessKey = accessKey;
        this.countryCode = countryCode;
    }
}