0

I want to encrypt data and write it in my database. This works fine. After I get the data back from my database I want to decrypt this data, but the decryption doesn't work correctly.

I saved the string "test" in the database. The encryption works correctly and the encrypted string is

3ac5d5d6beeb44c5a58ac54e7fc0ad07ea3c819ff6489aae16d490667a309751378ae10800c072551e3a97596f3a2ae0

after i run the decrypt function i get back this:

8ea2e28e0086ef2ad22c2d7805a34111

but it should be "test"

const crypto = require("crypto");
const algorithm = "aes-256-cbc";
const key = new Buffer("11111111111111111111111111111111");
const iv = new Buffer("12345678");

module.exports = {

//my encyrpt function

  encrypt(text) { 
    let ivstring = iv.toString("hex");

    let cipher = crypto.createCipheriv(algorithm, key, ivstring);
    let encrypted = cipher.update(text);
    encrypted = Buffer.concat([encrypted, cipher.final()]);
    //  return { iv: iv.toString("hex"), encryptedData: encrypted.toString("hex") };
    return encrypted.toString("hex");
  },

// my decrypt data

 decrypt(text) {
   let ivstring = iv.toString("hex");
   let encryptedText = Buffer.from(text, "hex");
    let decipher = crypto.createDecipheriv(algorithm, key, ivstring);
    let decrypted = decipher.update(encryptedText);
    decrypted = Buffer.concat([decrypted, decipher.final()]);
    return decrypted.toString();
  }
};
cmlonder
  • 2,370
  • 23
  • 35
Josef Henn
  • 125
  • 4
  • 18

1 Answers1

2

It seems that you have applied the encryption twice:

encrypt(encrypt('test')) 
// returns '3ac5d5d6beeb44c5a58ac54e7fc0ad07ea3c819ff6489aae16d490667a309751378ae10800c072551e3a97596f3a2ae0'

So you can decipher it by calling decrypt twice on the ciphertext:

const cipherText = '3ac5d5d6beeb44c5a58ac54e7fc0ad07ea3c819ff6489aae16d490667a309751378ae10800c072551e3a97596f3a2ae0'
decrypt(decrypt(cipherText))
// returns 'test'
antonku
  • 7,377
  • 2
  • 15
  • 21
  • ok you are totally right, i called teh encryption two times. now i have another problem, if the string is longer than 5 characters i get an error : error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length any advise :) – Josef Henn Aug 02 '19 at 09:21
  • Hi @JosefHenn, Unfortunately, I cannot replicate the issue with a plaintext longer that 5 characters (node v10.16.0). You can check answers to the following [question](https://stackoverflow.com/questions/21292142/decrypting-aes256-with-node-js-returns-wrong-final-block-length), they may be relevant. – antonku Aug 02 '19 at 10:34