const crypto = require('crypto');
const algorithm = 'aes-256-cbc';

function pkGenerateKey(pkSecret) {
  const salt = crypto.randomBytes(16);
  const key = crypto.pbkdf2Sync(pkSecret, salt, 100000, 32, 'sha256');
  return { key, salt };
}

function pkGenerateIV() {
  return crypto.randomBytes(16); // 16 bytes (128 bits) IV
}

function pkBytesToHex(buffer) {
  return buffer.toString('hex');
}

function pkHexToBytes(hex) {
  return Buffer.from(hex, 'hex');
}

function pkEncrypt(text, pkSecret) {
  const { key, salt } = pkGenerateKey(pkSecret);
  const iv = pkGenerateIV();
  let cipher = crypto.createCipheriv(algorithm, key, iv);
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return { iv: pkBytesToHex(iv), salt: pkBytesToHex(salt), encryptedData: encrypted };
}

function pkDecrypt(data, pkSecret) {
  let iv = pkHexToBytes(data.iv);
  let encryptedText = pkHexToBytes(data.encryptedData);
  let key = crypto.pbkdf2Sync(pkSecret, pkHexToBytes(data.salt), 100000, 32, 'sha256');
  let decipher = crypto.createDecipheriv(algorithm, key, iv);
  let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  return decrypted;
}

function pkGenerateHash(text) {
  const hash = crypto.createHash('sha256').update(text).digest('hex');
  return hash.slice(0, 14); // Take the first 14 characters of the hash
}

var pkSecret = '1234567890123456';
var pkEncryptedData = pkEncrypt("tocopyengineer", pkSecret);
console.log(pkEncryptedData);
console.log("Encrypted code:", pkGenerateHash(pkEncryptedData.encryptedData));

console.log("Decrypted text:", pkDecrypt(pkEncryptedData, pkSecret));


Output-  

Encrypted code: 8e2786d991e9ea

Decrypted text: hellotocopyengineer