AES-GCM-Util - For Bpay Only

Encryption for the payload body

Java Example:

import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;

public class AESGCMUtil {
    
    public static final int GCM_TAG_LENGTH = 16;

    private AESGCMUtil() {}

    public static String encrypt(String plainText, String secKey, String ivData) throws GeneralSecurityException {
        Cipher cipher = buildCipher(secKey, ivData, Cipher.ENCRYPT_MODE);
        byte[] cipherText = cipher.doFinal(plainText.getBytes());
        return byteToHex(cipherText);
    }

    public static String byteToHex(byte[] byteData) {
        StringBuilder stringBuilder = new StringBuilder(byteData.length*2);
        for(byte hashByte: byteData) {
            stringBuilder.append("%02x".formatted(hashByte));
        }
        return stringBuilder.toString().toUpperCase();
    }


    private static byte[] hexToByteArray(String hexString) {
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                    + Character.digit(hexString.charAt(i + 1), 16));
        }
        return data;
    }

    private static Cipher buildCipher(String secretKey, String ivData, int cipherMode) throws GeneralSecurityException {
        SecretKeySpec keySpec = new SecretKeySpec(hexToByteArray(secretKey), "AES");
        GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, hexToByteArray(ivData));
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(cipherMode, keySpec, gcmParameterSpec);
        return cipher;
    }

}

Last updated

Was this helpful?