Home > database >  Is it possible to encrypt (not hash!) and use a salt?
Is it possible to encrypt (not hash!) and use a salt?

Time:09-15

I am encrypting objects using Node.js native crypto methods like createCipherIv.

const algorithm = "aes256";
const inputEncoding = "utf8";
const outputEncoding = "hex";
const iv = randomBytes(16);

export async function encryptObject(dataToEncrypt: object, key: Buffer) {
  const clear = JSON.stringify(dataToEncrypt);

  const cipher = createCipheriv(algorithm, key, iv);
  let ciphered = cipher.update(clear, inputEncoding, outputEncoding);
  ciphered  = cipher.final(outputEncoding);

  return iv.toString(outputEncoding)   ":"   ciphered;
}

Sometimes I am encrypting the same object multiple times and send it over http(s). That makes me think a man in the middle could observe that communication and maybe gain information about my user by using something like a Rainbow table to map the encrypted Data to real data over time.

Now I'm not sure if my worries make sense, but I'm thinking, that my encryption could be more secure if a add a salt to it. So far I've only come accross salt when hashing, not encrypting. Hashing is not an option for me, because I cannot rely on hashes to be equivalent. I actually have to do something with the data, so I have to be able to decrypt it again.

So my questions are:

  1. Do my thoughts add up, and I would be better of adding salt?
  2. Is it possible to use Node.js native crypto functions for symmetric encryption while adding salt to the mechanism in order to have different encrypted results on every run?

CodePudding user response:

Basically the IV is your salt. That's it purpose (apart from initializing the chaining algorithm). So you are ok with the code you posted here. Initialization vector is random so the encrypted bytes will be different every time.

Just check it with the simple console.log you will see that resulting bytes are totally different every time.

On the other hand I don't think that this (identical encrypted bytes) is much of a concern here. I would make rather sure that the chaining method is at least CBC. Here you can read more about it: https://en.m.wikipedia.org/wiki/Block_cipher_mode_of_operation

Also if you want to be super secure with the man in the middle attack. You can add some HMAC to your message. This will ensure that no one can flip a bit in your message to make it different. In other words it provides

data integrity and authenticity of a message.

But still if you send data over httpS, all of those safety measures are already in place. Hence the name of the examplary https cipher: tls_dhe_rsa_with_aes_256_gcm_sha384. Extracting the things that I mentioned here. It uses aes256 with gcm chaining mode and sha348 as a hashing method for the hmac.

  • Related