title: Read and use private key to sign data in node js [OpenSSL & PHP Example]
body: <p>I've been trying for a while to rewrite a php code into node.js, but I've encountered a problem.</p>
  
  <p>This is the PHP code I'm stuck on (a little bit modified):</p>
  
  <pre><code>$fp = fopen($privateKeyFileName, "r");
  $priv_key = fread($fp, 8192);   
  fclose($fp);
  
  echo "PRIVATE KEY: &lt;br/&gt;&lt;br/&gt;";
  var_dump($priv_key);
  
  
  $pkeyid = openssl_pkey_get_private($priv_key, $privateKeyPassword);
  
  echo " &lt;br/&gt;&lt;br/&gt;PRIVATE KEY ID: &lt;br/&gt;&lt;br/&gt;";
  var_dump($pkeyid);
  
  openssl_sign($message, $signature, $pkeyid);
  openssl_free_key($pkeyid);
  
  echo " &lt;br/&gt;&lt;br/&gt;SIGNATURE: &lt;br/&gt;&lt;br/&gt;";
  var_dump($signature);
  
  $message .= $signature;
  
  echo " &lt;br/&gt;&lt;br/&gt;END MESSAGE: &lt;br/&gt;&lt;br/&gt;";
  var_dump($message);
  </code></pre>
  
  <p>The part I'm stuck on is: <code>openssl_pkey_get_private</code>. I'm not sure how to replicate it. I tried skipping it, a let <code>crypto</code> (nodejs) do the work, but with no luck.</p>
  
  <p>The interesting thing that needs to be done is: everytime, when I sign the message, <code>$signature</code> has 128 characters (string). This is an requirement, and this is my problem in node.</p>
  
  <p>This is my nodejs code:</p>
  
  <pre><code>function signData(data) {
      var sign = crypto.createSign('RSA-SHA256');
      sign.update(data);
      var signed = sign.sign(privateKey);
      return signed;
  }
  </code></pre>
  
  <p>And another thing, this <code>RSA-SHA256</code> has to be SHA1withRSA. This example never generates exactly 128 char string. It returns a buffer, and no matter how I parse or convert it, I can't achieve the requirement. I'm using the same private key on both examples.</p>
  
  <p>Any ideas? </p>