node.js - 使用 Node.js 加密文本文件中的各个行

标签 node.js encryption cryptojs

我正在尝试加密文本文件中的每一行,而不是文本文件本身。这是我用于加密单行文本的代码。

crypto.pbkdf2(password, salt, iteration, keylen, digest, (error, derivedKey) => {
    const iv = Buffer.from('myiv', 'hex');

    const cipher = crypto.createCipheriv(algorithm, derivedKey, iv);

    let encryptThis = `Encrypt me`;
    let encrypted = '';

    cipher.on('readable', () => {
        let chunk;
        while (null !== (chunk = cipher.read())) {
            encrypted += chunk.toString('base64');
        }
    });

    cipher.on('end', () => {
        console.log(`Example string:   ${encryptThis}`);
    });

    cipher.write(encryptThis);
    cipher.end();
});

我知道我也可以使用 cipher.update(text)cipher.final() 进行加密,并且也尝试过这种方法,但没有成功。问题是如何逐行读取文件并加密每一行。我已经尝试了这两种方法,但它总是导致只有一行被加密或出现错误。我希望能够通过流转换之类的东西来做到这一点。

readStream
    .pipe(encryptLine)
    .pipe(writeStream)
    .on('finish', err => {
        if (err) console.log(err);
    });

最佳答案

我首先会实现一个转换流(或利用现有的库)来逐行读取文件。

function toLines() {
    let line = '';
    return new Transform({
        decodeStrings: false,
        readableObjectMode: true,
        transform(chunk, encoding, callback) {
            const lines = chunk.split(/\r?\n/g);

            line += lines.shift();
            while (lines.length) {
                this.push(line);
                line = lines.shift();
            }

            callback();
        },
        flush(callback) {
            if (line) {
                this.push(line);
            }
            callback();
        }
    });
}

然后我将实现一个转换流来加密每一行。

function encryptLines(algorithm, derivedKey, iv) {
    return new Transform({
        readableObjectMode: false,
        writableObjectMode: true,
        transform(line, encoding, callback) {
            const cipher = crypto.createCipheriv(algorithm, derivedKey, iv);
            this.push(cipher.update(line, encoding, 'base64'));
            this.push(cipher.final('base64'));
            this.push('\n');
            callback();
        }
    });
}

然后您可以简单地将所有内容管道到输出流(根据需要)。

fs.createReadStream('input.txt', {encoding: 'utf8'})
    .pipe(toLines())
    .pipe(encryptLines(algorithm, derivedKey, iv))
    .pipe(fs.createWriteStream('output.txt'))
    .on('finish', () => console.log('done'));

关于node.js - 使用 Node.js 加密文本文件中的各个行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55789017/

相关文章:

javascript - MongoDB $and 查询不适用于变量查询字符串

javascript - 语法错误 : Missing initializer in destructuring declaration

ruby-on-rails - 如何在我的 Rails 数据库中加密 OAuth secret / token ?

javascript - AES 加密中的 CryptoJS 额外参数。如何使用 PHP 进行复制?

reactjs - 类型错误 : null is not an object (evaluating 'RNRandomBytes.seed' ) React Native

authentication - 在 node.js 中生成和验证 session

node.js - Nodejs获取相对于process.cwd()的绝对路径

node.js - 如何将环境变量从文件传递到 Node 命令

php - NCFB 和 NOFB 模式有何用途?

Java:在 HTTP Post 中发送带有其他参数的 byte[]