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;