Alon Carmel
Alon Carmel

Reputation: 710

Nodejs Crypto decrypt fails after one successful encryption and decryption

I got a weird scenario on nodejs where crypto works encryption and decryption of text only once when i load the node server. After the second try it encrypts the text fine but is unable to decrypt the text on second try.

This is my code:

function Encrypt(mytext) {
  var cipher = crypto.createCipher('aes-256-cbc','fa97be5d286a67114cf74acf46d179725581d562');
  var crypted = cipher.update(mytext,'utf8','hex');
  crypted += cipher.final('hex');
}

function Decipher(mytext) {
  var decipher = crypto.createDecipher('aes-256-  cbc','fa97be5d286a67114cf74acf46d179725581d562');
  var dec = decipher.update(mytext,'hex','utf8');
  dec += decipher.final('utf8');
}

This works fine ONCE the nodejs server loads, encrypt and decrypts the data perfectly, the second time this function is used elsewhere with a different text or key it fails to decrypt the text. I'm puzzled.

Upvotes: 3

Views: 1113

Answers (1)

Alon Carmel
Alon Carmel

Reputation: 710

This was resolved after i've added:

delete require.cache[require.resolve('./templates/prd')];

The required object stayed in cache and continued to be encrypted over and over. once i cleared the cache everytime i loaded the template it started encrypting it properly.

Upvotes: 2

Related Questions