【发布时间】:2021-03-26 21:43:56
【问题描述】:
我需要保护电子应用程序的用户输入密码,以创建用于加密 AES 加密的密钥。正如这里所建议的那样,我已经用scryptSync 函数替换了createHash 函数。我不确定盐的情况。
// this is the old method I've used to hash the password to obtain the correct lenght for aes-256-gcm
// let key = crypto.createHash('sha256')
// .update(data.password)
// .digest();
// salt creation
let salt = crypto.randomBytes(64);
let key = crypto.scryptSync(data.password, salt, 32);
对于aes-256-gcm 加密算法,我需要传递给randomBytes 函数的预定义大小吗?
另外,当我将盐附加到加密输出时,我正在使用此代码
let encryptedData = Buffer.concat([cipher.update(base64, 'utf8'), cipher.final()]);
let payload = `${salt.toString('base64')}:${iv.toString('base64')}:${encryptedData.toString('base64')}`;
由于我使用join() 函数来合并多个编码字符串,因此当需要对加密的输出文件进行解码时,我需要一种方法来拆分它们。目前我正在使用这种方式,但我发现我需要提取盐来检查密码。有没有更好的办法?
const decryptData = (data) => {
let output = [];
// I need the salt here but the file needs to be splitted before
let key = crypto.scryptSync(data.password, 'salt', 32);
return new Promise( (resolve, reject) => {
fs.readFile(data.path, 'utf8', (err, content) => {
if(err) return reject(err);
let fileContents = content.split(' ');
output = fileContents.map( (file) => {
let [salt, iv, content] = file.split(':');
let cipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(iv, 'base64'));
let decrypted = cipher.update(content, 'base64', 'utf8');
return decryptedData;
});
resolve(output);
});
});
}
【问题讨论】:
标签: node.js encryption salt