Home > Net >  Encrypt nodejs data to mysql
Encrypt nodejs data to mysql

Time:04-19

I'm currently using Crypto to encrypt/ decrypt data, but, if the server restarts, the decrypt won't work anymore. That's what i'm currently using =>

const crypto = require("crypto");
const algorithm = "aes-256-cbc"; 
const initVector = crypto.randomBytes(16);
const Securitykey = crypto.randomBytes(32);

function encrypt(text){
    const cipher = crypto.createCipheriv(algorithm, Securitykey, initVector);
    let encryptedData = cipher.update(text, "utf-8", "hex");
    encryptedData  = cipher.final("hex");
    return encryptedData;
}

function decrypt(text){
    const decipher = crypto.createDecipheriv(algorithm, Securitykey, initVector);
    let decryptedData = decipher.update(text, "hex", "utf-8");
    decryptedData  = decipher.final("utf8");
    return decryptedData;
}

And this is the error I get if i want to decrypt something after server restart

Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt

CodePudding user response:

So as I can see from the code your IV and Key are randomly generated and I am assuming that you are not saving them anywhere.

const initVector = crypto.randomBytes(16);
const Securitykey = crypto.randomBytes(32);

So basically on server restart you are getting a new pair of IV and key, so when you are decrypting it is not matching with the Key and IV used at the time of encryption.

My suggested solution :

const crypto = require("crypto");
const algorithm = "aes-256-cbc"; 
const initVectorString = 'Any random string'; // You can store this into a env file
const SecuritykeyString = 'Random security string'; // You can store this into a env file
const initVector = Buffer.from(initVectorString, 'hex');  
const Securitykey = Buffer.from(SecurityKeyString, 'hex');

function encrypt(text){
    const cipher = crypto.createCipheriv(algorithm, Securitykey, initVector);
    let encryptedData = cipher.update(text, "utf-8", "hex");
    encryptedData  = cipher.final("hex");
    return encryptedData;
}

function decrypt(text){
    const decipher = crypto.createDecipheriv(algorithm, Securitykey, initVector);
    let decryptedData = decipher.update(text, "hex", "utf-8");
    decryptedData  = decipher.final("utf8");
    return decryptedData;
}
  • Related