有没有办法用一些秘密密钥获得相同的加密哈希值?

问题描述

我想以加密格式加密敏感数据并将其保存到db。但后来我必须能够使用用于解密的密钥进行解密。重要的是,加密必须始终提供相同的哈希值。


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?

解决方法

首先,您的密钥将是相同的 key 值。因为要散列的值将为空。

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

您的结果将总是不同,因为 IV 在每次执行中都是随机的。因此,您可以将 IV 存储在数据库中、最终消息中,或者根据键或数据等其他值使用唯一值。

如果您将 IV 保存在数据库中或将其公开,则不会存在安全风险。

参考: