Javascript NodeJS exec与进程之间的二进制文件
我正在尝试编写一个函数,它将使用原生openssl为我完成一些RSA繁重的工作,而不是使用js RSA库。目标是Javascript NodeJS exec与进程之间的二进制文件,javascript,node.js,exec,rsa,Javascript,Node.js,Exec,Rsa,我正在尝试编写一个函数,它将使用原生openssl为我完成一些RSA繁重的工作,而不是使用js RSA库。目标是 从文件中读取二进制数据 在节点进程中使用JS进行一些处理,生成包含二进制数据的缓冲区 将缓冲区写入exec命令的stdin流 RSA加密/解密数据并将其写入标准输出流 将输入数据返回到JS进程中的缓冲区以进行进一步处理 in节点有一个exec命令,但我看不出如何将输入通过管道传输到进程并将其返回到进程。基本上,我希望执行以下类型的命令,但不必依赖于将内容写入文件(没有检查openss
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);
}
你提到了,但似乎认为你不能使用它。这里可能显示了我的无知,但它似乎正是您想要的:通过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'});
我希望这有帮助 在调用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'});
我希望这有帮助