Dinger

Developer / Prebuilt Checkout API / Payload and Redirect

Encryption & Decryption data


Node

In node JS, you have to install a library, aes-ecb that helps you with encrypting and decrypting base64 payload.





                                        
import aesEcb from 'aes-ecb';

const secret_key = 'yoursecretkey1231231231231231231';
const data = {
    totalAmount: 3000,
    createdAt: '20210927 154445',
    transactionStatus: 'SUCCESS',
    methodName: 'QR',
    merchantOrderId: '4',
    customerName: 'John Doe',
    transactionId: 'TRX390920214427154445',
    providerName: 'KBZ Pay',
};

// This encrypts the data payload
const encrypted_data = aesEcb.encrypt(secret_key, JSON.stringify(data));

// This decrypts the data payload, returning the original data
const decrypted_data = aesEcb.decrypt(secret_key, encrypted_data);

console.log(encrypted_data, decrypted_data);

Decryption Code Sample



                                        
public static byte[] encrypt(String data, String publicKey) throws BadPaddingException, IllegalBlockSizeException, InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException {
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKey));
    byte[] enBytes = null;
    int i = 0;
    while (i < data.length()) {
        byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(data.getBytes(), i, i + 64));
        enBytes = ArrayUtils.addAll(enBytes, doFinal);
        i += 64;
    }
    return enBytes;
}

public static PublicKey getPublicKey(String base64PublicKey){
        PublicKey publicKey = null;
        try{
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(base64PublicKey.getBytes()));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            publicKey = keyFactory.generatePublic(keySpec);
            return publicKey;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return publicKey;