Skip to main content
When initiating or managing your payments and orders, you must encrypt your data before making the request. If you send an unencrypted request to an endpoint that requires encryption, you will receive a 401 error.
400 Bad Request
{
    "status": "failed",
    "statusCode": "400",
    "message": "Unable to find the encrypted data, please encrypt your payload and try again"
}
To encrypt your request payload, you will need to fetch your encryption key from your dashboard (learn more here). Our encryption uses the RSA algorithm to encrypt data, you can read up about RSA encryption here. We’ve included some examples in this guide to help you encrypt your requests.
  1. Retrieve your encryption key.
  2. Decode your key using base64.
  3. Split the result into an array with two elememts using ”!” as a delimiter.
  4. Extract your RSA public key as array[1] from the array in step 3.
  5. Encrypt using the RSA public key returned in step 4.
const forge = require('node-forge');
const NodeRSA = require('node-rsa');
const {DOMParser} = require('xmldom');

function encrypt(message, merchantEncryptionKey) {
    const encPemKey = getRsaEncryptionKey(merchantEncryptionKey);

    console.log(encPemKey);

    const encryptKey = new NodeRSA(encPemKey);
    encryptKey.setOptions({
        encryptionScheme: 'pkcs1'
    });


    const encryptedMessage = encryptKey.encrypt(message, 'base64');

    if (encryptedMessage) {
        console.log('Encrypted Message:', encryptedMessage);
    } else {
        console.error('Encryption failed.');
    }
    return encryptedMessage;
}

function getRsaEncryptionKey(merchantEncryptionKey) {
    // Decode the Base64 string
    const decodedKey = Buffer.from(merchantEncryptionKey, 'base64').toString('utf-8').split('!');
    console.log(decodedKey);

    const rsaXml = decodedKey[1];
    console.log(rsaXml);

    return xmlToPem(rsaXml);
}

function xmlToPem(xmlKey) {
    const parser = new DOMParser();
    const xmlDoc = parser.parseFromString(xmlKey, 'text/xml');

    // Extract Modulus and Exponent
    const modulusBase64 = xmlDoc.getElementsByTagName('Modulus')[0].textContent;
    const exponentBase64 = xmlDoc.getElementsByTagName('Exponent')[0].textContent;

    console.log('modulusBase64:', modulusBase64);
    console.log('exponentBase64:', exponentBase64);

    const BigInteger = forge.jsbn.BigInteger;

    function parseBigInteger(b64) {
        return new BigInteger(forge.util.createBuffer(forge.util.decode64(b64)).toHex(), 16);
    }

    const publicKey = forge.pki.setRsaPublicKey(
        parseBigInteger(modulusBase64),
        parseBigInteger(exponentBase64)
    );

    // Convert a Forge public key to PEM-format
    const pem = forge.pki.publicKeyToPem(publicKey);

    return pem;
}

module.exports = encrypt;