const crypto = require('crypto');

/**
 * Encrypt the given data using AES/CBC/PKCS5.
 * 
 * @param {any} data The data to be encrypted
 * @param {string} key The key used for encryption
 * @param {string} iv The initialization vector used for encryption
 * 
 * @returns {string} The encrypted data in base64
 */
const encrypt = (data, key, iv) => {
  const keyDigest = crypto.createHash('sha256').update(key).digest();
  const cipher = crypto.createCipheriv('aes-256-cbc', keyDigest, iv).setAutoPadding(true);
  const json = JSON.stringify(data);
  const result = cipher.update(json, 'utf8', 'base64') + cipher.final('base64');

  return result;
};

module.exports = encrypt;