iv解码无效,并使用密码加密了字符串

问题描述

嗨,我有以下代码片段,可以在其中加密和解密诸如密码之类的严重字符串。

const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);

function encrypt(text) {
 let cipher = crypto.createCipheriv('aes-256-cbc',Buffer.from(key),iv);
 let encrypted = cipher.update(text);
 encrypted = Buffer.concat([encrypted,cipher.final()]);
 return { iv: iv.toString('hex'),encryptedData: encrypted.toString('hex') };
}

function decrypt(text) {
 let iv = Buffer.from(text.iv,'hex');
 let encryptedText = Buffer.from(text.encryptedData,'hex');
 let decipher = crypto.createDecipheriv('aes-256-cbc',iv);
 let decrypted = decipher.update(encryptedText);
 decrypted = Buffer.concat([decrypted,decipher.final()]);
 return decrypted.toString();
}

var hw = encrypt("Some serIoUs stuff")
console.log(hw)
console.log(decrypt(hw))

下面的两个控制台行可以正常工作。它可以加密然后立即解密。但是当我将加密的字符串另存为

{iv: '...',encryptedData: '...'} //from var hw

数据库并从数据库获取它并解密对象,它不起作用

我所知道的是,对象来自立即加密-解密中使用的同一变量 hw ,但在 encrypt-savetoDB-getFromDB中无效-解密

这对我来说很奇怪,还是我误解了加密和解密的整个过程。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)