'Getting invalidCiphertextException: null when decrypting data which was encrypted with kms public key

I am building a POC based on asymmetric encryption where the public key from KMS will be downloaded and used on the client side to encrypt sensitive data and once that data is received at the server end it needs to be decrypted using KMS decrypt function. Encryption and Decryption using KMS works fine but when I encrypt with the downloaded public key and then decrypt with KMS I get invalidCiphertextException: null

CMK Cryptographic Configuration is https://i.stack.imgur.com/0muAb.png

The code I use for encryption is

var encrypt_with_public_key = function (data) {
    let fs = require('fs'),
    path = require('path'),    
    absolutePath  = path.join(__dirname, 'Publickey.pem');   
    let publicKey = fs.readFileSync(absolutePath, "utf8");
    let encrypted = crypto.publicEncrypt({
        key: Buffer.from(publicKey),        
        oaepHash: "sha256",
    },Buffer.from(data)).toString("base64");
       
    
    return encrypted;
}

Code used for Decryption is

var decrypt_data = function (data) {
    try {
        let params = {
            KeyId: kmsConfig["KeyId"], 
            EncryptionAlgorithm: kmsConfig["EncryptionAlgorithm"] /* RSAES_OAEP_SHA_256*/
        }
        params.CiphertextBlob = Buffer.from(data)        
        return kms.decrypt(params).promise().then(data => data.Plaintext);
        
    }
    catch (ex) {
        throw ex
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source