繁体   English   中英

NodeJS exec与进程之间的二进制文件

[英]NodeJS exec with binary from and to the process

我正在尝试编写一个函数,该函数将使用本机openssl为我执行一些RSA重载操作,而不是使用js RSA库。 目标是

  1. 从文件中读取二进制数据
  2. 使用JS在节点进程中进行一些处理,从而导致包含二进制数据的Buffer
  3. 将缓冲区写入exec命令的stdin流
  4. RSA加密/解密数据并将其写入标准输出流
  5. 将输入数据返回到JS进程中的Buffer进行进一步处理

Node中的子流程模块具有exec命令,但是我看不到如何将输入传递给流程并将其传递回我的流程。 基本上,我想执行以下类型的命令,但不必依赖于将事情写到文件中(不必检查openssl的确切语法)

cat the_binary_file.data | openssl -encrypt -inkey key_file.pem -certin > the_output_stream

我可以通过写一个临时文件来做到这一点,但是如果可能的话,我想避免它。 生成子进程使我可以访问stdin / out,但尚未找到exec的此功能。

有没有一种干净的方法可以按照我在这里草拟的方式进行? 是否有一些使用openssl的替代方法,例如,一些针对openssl lib的本机绑定,可以让我无需依赖命令行即可执行此操作?

您已经提到了spawn但似乎认为您无法使用它。 可能在这里显示出我的无知,但似乎应该正是您想要的:通过spawn启动openssl,然后写入child.stdin并从child.stdout读取。 类似于完全未经测试的代码:

var util  = require('util'),
    spawn = require('child_process').spawn;

function sslencrypt(buffer_to_encrypt, callback) {
    var ssl = spawn('openssl', ['-encrypt', '-inkey', ',key_file.pem', '-certin']),
        result = new Buffer(SOME_APPROPRIATE_SIZE),
        resultSize = 0;

    ssl.stdout.on('data', function (data) {
        // Save up the result (or perhaps just call the callback repeatedly
        // with it as it comes, whatever)
        if (data.length + resultSize > result.length) {
            // Too much data, our SOME_APPROPRIATE_SIZE above wasn't big enough
        }
        else {
            // Append to our buffer
            resultSize += data.length;
            data.copy(result);
        }
    });

    ssl.stderr.on('data', function (data) {
        // Handle error output
    });

    ssl.on('exit', function (code) {
        // Done, trigger your callback (perhaps check `code` here)
        callback(result, resultSize);
    });

    // Write the buffer
    ssl.stdin.write(buffer_to_encrypt);
}

调用exec时,应该应该能够将编码设置为二进制,例如。

exec("openssl output_something_in_binary", {encoding: 'binary'}, function(err, out, err) {
   //do something with out - which is in the binary format
});

如果要用二进制写出“ out”的内容,请确保再次将编码设置为二进制,例如。

fs.writeFile("out.bin", out, {encoding: 'binary'});

我希望这有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM