Lupu Claudiu
Lupu Claudiu

Reputation: 25

Encrypt nodejs data to mysql

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

Upvotes: 1

Views: 1356

Answers (1)

Jay Godhani
Jay Godhani

Reputation: 396

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 hex string of 16bytes"; // You can store this into a env file
const SecuritykeyString = "Random security hex string of 32bytes"; // 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;
}

Update:-

So if you are using a utf-8 string for IV then the string length should be 16 characters only (if you are using only 1 byte characters a-zA-Z0-9 all are 1 byte characters) and you need to change the encoding type in Buffer.from() function from "Hex" to "utf-8".

Similar for the security key length of the string should be 32 characters only and you need to change the encoding type in Buffer.from() function from "Hex" to "utf-8".

Upvotes: 2

Related Questions