How to Encrypt and Decrypt data with NodeJs crypto

Ernesto Jara Olveda
2 min readJul 16, 2020

--

Today I will show you what every do not tells you when encrypting and decrypting.

Lets start by importing crypto, as that is what we need xDD.

const crypto = require("crypto");

Something very important that almost everybody do not tells you on their tutorials and stuff, is the fact that to decrypt you need the same keys and stuff you used to encrypt the data.

so if you see something like this:

const someVarName = crypto.randomBytes(16);

you might be able to encrypt yow data, but wont be able to decrypted back, the reason lives on the “randomBytes” name. that things returns random bytes.

Photo by Patrick Fore on Unsplash

and youll end up finding yourself on stackoverflow. trying to fix then SSL configs.

so in our file lets add our secret keys and stuff.

const crypto = require("crypto");const iv = process.env.PROD_IV || "not-prod";
const iv = process.env.PROD_KEY || "not-prod-ass-well";

lets also add the algorithm we are going to use

....
const algorithm = "aes-256-cbc";

then put the hasher xDD this method is going to hash your secrets.


function
scrypt (num, secret) {
return new Promise((res, rec) => {
return crypto.scrypt(secret, "salt", num, (err, key) => {
if (err) return rec(err);
return res(key);
});
});
}
// https://nodejs.org/api/crypto.html#crypto_crypto_scrypt_password_salt_keylen_options_callback

As long as we pass the same parameters into that function, we are going to get the same data.

for the iv and the key we do.

...
function
getIv () {
return scrypt(8, iv).then((response) => response.toString("hex"));
}
function getKey () {
return scrypt(32, key).then((response) => response);
}

Now let us create the encrypter

Lets do the decrypter as well… lets put the whole thing together

Remember!!

If you do not want to endup looking at why the F* SSL is not working

Do not forget to use the same iv and key for both methods

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response