DEV Community

KISHAN RAMLAKHAN NISHAD
KISHAN RAMLAKHAN NISHAD

Posted on

Create Encryption and Decryption function using npm CryptoJS

const CryptoJS = require('crypto-js');

function randomString(length) {
  var text = '';

  var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

  for (var i = 0; i < length; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }

  // var key = text + navigator.sayswho + $(window).width();

  var key = text;

  return key;
}



exports.CareerDecrypt = async cipherData => {
  if (process.env.ENABLE_ENCERIPTION == 0) return cipherData;
  console.log('cipherData', cipherData);
  if (!cipherData) {
    console.log('cipherData', cipherData);
    throw Error('somthing went wrong !!');
  }

  var key = CryptoJS.enc.Utf8.parse('$k@m0u$0172@0r!k$k@m0u$0172@0r!k');
  var iv = CryptoJS.enc.Utf8.parse(cipherData.slice(cipherData.length - 16));
  cipherData = cipherData.slice(0, cipherData.length - 16);
  var decrypted = CryptoJS.AES.decrypt(cipherData, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });
  // console.log("here",decrypted.toString(CryptoJS.enc.Utf8))
  let Jsondata = JSON.parse(`${decrypted.toString(CryptoJS.enc.Utf8)}`);

  return Jsondata;
};

exports.CareerEncrypt = plain => {
  if (process.env.ENABLE_ENCERIPTION == 1) {
    let randomIV = randomString(16);
    var key = CryptoJS.enc.Utf8.parse('$k@m0u$0172@0r!k$k@m0u$0172@0r!k');
    var iv = CryptoJS.enc.Utf8.parse(randomIV);
    // var iv = CryptoJS.enc.Utf8.parse("@1O2j3D4e5F6g7P8");
    // console.log(iv, randomIV);
    var encrypted = CryptoJS.AES.encrypt(JSON.stringify(plain), key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    });

    let encrypt = encrypted.toString() + randomIV;
    console.log(encrypt.replace(/\\/g, '/'));
    return encrypt.replace(/\\/g, '/');
  } else {
    console.log('err');
    return plain;
  }

  // return encrypted.toString();
};

exports.CareerEncryptold = async plain => {
  if (process.env.ENABLE_ENCERIPTION == 1) {
    let randomIV = randomString(16);
    var key = CryptoJS.enc.Utf8.parse('$k@m0u$0172@0r!k');
    var iv = CryptoJS.enc.Utf8.parse(randomIV);
    var encrypted = CryptoJS.AES.encrypt(JSON.stringify(plain), key, {
      keySize: 128 / 8,
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    });

    let encrypt = encrypted.toString() + randomIV;
    return encrypt.replace(/\\/g, '/');
  } else {
    return plain;
  }

  // return encrypted.toString();
};

exports.eSettlementEncrypt = async plainText => {
  try {
    // Define the encryption key and initialization vector (IV)
    const secretKey = CryptoJS.enc.Utf8.parse('8080808080808080');
    const iv = CryptoJS.enc.Utf8.parse('8080808080808080');

    // Encrypt the plain text
    const encrypted = CryptoJS.AES.encrypt(JSON.stringify(plainText), secretKey, {
      keySize: 128 / 8,
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    });

    // Return the encrypted string
    const encryptedString = encrypted.toString();
    console.log('Encrypted Text:', encryptedString);
    return encryptedString;
  } catch (error) {
    console.error('Encryption Error:', error.message);
    throw new Error('Encryption failed');
  }
};

exports.eSettlementDecrypt = async cipherData => {
  try {
    if (!cipherData) {
      console.log('cipherData is missing:', cipherData);
      throw new Error('Decryption failed: cipherData is required.');
    }

    // Define the decryption key and initialization vector (IV)
    const secretKey = CryptoJS.enc.Utf8.parse('8080808080808080');
    const iv = CryptoJS.enc.Utf8.parse('8080808080808080');

    // Decrypt the cipher text
    const decrypted = CryptoJS.AES.decrypt(cipherData, secretKey, {
      keySize: 128 / 8,
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    });

    // Convert the decrypted data back to UTF-8 and parse JSON
    const decryptedText = decrypted.toString(CryptoJS.enc.Utf8);
    const jsonData = JSON.parse(decryptedText);

    return jsonData;
  } catch (error) {
    console.error('Decryption Error:', error.message);
    throw new Error('Decryption failed');
  }
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)