2011-11-10 47 views
1

我正在嘗試編寫一個函數,它會使用本機openssl爲我做一些RSA繁重工作,而不是使用js RSA庫。目標是NodeJS執行程序與進程的二進制

  1. 從文件
  2. 讀取二進制數據做一些處理在節點過程中,採用JS,導致緩衝器包含二進制數據
  3. 寫緩衝器給exec的STDIN流命令
  4. RSA加密/解密數據,並將其寫入stdout流
  5. 獲取輸入數據返回到在JS-處理的緩衝液用於進一步處理

Node中的child process module有一個exec命令,但我沒有看到如何將輸入傳遞給進程並將其傳回到我的進程。基本上,我想執行以下命令的類型,但不必依靠書面的東西文件寫入一個臨時文件(沒有檢查的OpenSSL的確切語法)

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

我能做到這一點,但如果可能的話,我想避免它。產生一個子進程允許我訪問stdin/out,但沒有找到exec的這個功能。

有沒有一個乾淨的方式來做到這一點,我在這裏起草的方式?有沒有其他的方法可以使用openssl,例如openssl lib的一些本地綁定,這將允許我在不依賴命令行的情況下執行此操作?

回答

4

你提到過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); 
} 
1

您應該能夠設置編碼爲二進制當你調用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'}); 

我希望這有助於!