Search code examples
node.jsencryptionnode-crypto

Is there a way to get same encrypted hash value with some secret key?


I want to encrypt sensitive data in an encrypted format and save it to db. But later I have to be able to decrypt with a secret key used to decrypt. Importantly, encryption must give always the same hash.


const algorithm = 'aes256';
const iv = crypto.randomBytes(16).toString('hex').slice(0, 16);
const key = crypto
  .createHash('sha256')
  .digest('base64')
  .substr(0, 32);

const cipher = crypto.createCipheriv(algorithm, key, iv);
const encrypted =
  cipher.update(String('tobeEncrypted'), 'utf8', 'hex') + cipher.final('hex');

console.log(encrypted); 
console.log(encrypted); 
//e08f733a4dace8b22db763cbd2d0029e
//90086251f083c33dd6aa017a2c6f35f4

// How can I always get the same hash value?

Solution

  • First, your key will be the same key value. Because the value to be hashed will be empty.

    const key = crypto
      .createHash("sha256") // Hash algorithm
      .update(process.env.SECRET_KEY) // Data to hash
      .digest('base64')
      .substr(0, 32);
    

    Your result will be always different because the IV is random in each execution. So, you could store the IV in the database, in the final message, or use a unique depending on other values like the key or the data.

    There is no security risk if you save the IV in your database or if you expose it.

    Refs: