title: RSA sign in node.js and verify in C++
body: <p>I'm working on a way to secure the message I sent from a node.js server to a C++ application. </p>
  
  <p>From node.js , I created a key pair.</p>
  
  <p>I'm using node-rsa to read the public key on node.js side  ( <a href="https://github.com/rzcoder/node-rsa" rel="nofollow noreferrer">https://github.com/rzcoder/node-rsa</a> ) </p>
  
  <pre><code>var rsa =  new nodeRSA(publicKeyBuffer  ,{encryptionScheme :'pkcs1'})
  </code></pre>
  
  <p>As my message can be long, I calculate a salted sha256 of the message before calling encrypt. </p>
  
  <pre><code>const hash = crypto.createHash('sha256').update(message + config.signSalt).digest('hex')
  </code></pre>
  
  <p>this part is working fine because I am able to generate the exact same hash on C++ side.</p>
  
  <p>then, I'm calling the encrypt function of node-rsa to generate a buffer</p>
  
  <pre><code>const signature = rsa.encrypt(hash)
  </code></pre>
  
  <p>I tried various encoding , but as the data is sent through a websocket (+ MsgPack packing) the binary format is a good option</p>
  
  <p>On C++ side , I am first reading the key for a char[] </p>
  
  <pre><code>const char keyStr[] = "-----BEGIN RSA PRIVATE KEY-----\n" ..........
  
  BIO* bio = BIO_new_mem_buf(keyStr, (int)strlen(keyStr)); // -1: assume string is null terminated
  
  m_rsaPrivKey = PEM_read_bio_RSAPrivateKey(bio, NULL, NULL, NULL);
  
  if (!m_rsaPrivKey)
          LogOutSys("ERROR: Could not load PRIVATE KEY! PEM_write_bio_RSAPrivateKey FAILED: %s\n", ERR_error_string(ERR_get_error(), NULL));
  </code></pre>
  
  <p>the key is read without errors, after that, I'm calculating the hash from the message, making a std::string from the unsigned char buffer </p>
  
  <pre><code>std::string hash = sha256(msg.c_str());
  
  std::string signatureStr(signature.begin(), signature.end());
  
  char *decrypt;
  
  int decryptLen;
  
  decrypt = new char[RSA_size(m_rsaPrivKey)];
  
  decryptLen = RSA_private_decrypt((int)msg.size() + 1, (unsigned char*)msg.c_str(), (unsigned char*)decrypt, m_rsaPrivKey, RSA_NO_PADDING /* RSA_PKCS1_OAEP_PADDING */ );
  
  if (decryptLen == -1)
  {
      char errStr[130];
      ERR_error_string(ERR_get_error(), errStr);
      LogOutSys("Rsa::decrypt - Error decrypting string ssl error %s", errStr);
  }
  
  for (int i = 0; i &lt; decryptLen; i++)
  {
      decryptData.push_back(decrypt[i]);
  }
  
  delete decrypt;
  </code></pre>
  
  <p>the decrypt failed with the following error </p>
  
  <p>Rsa::decrypt - Error decrypting string ssl error error:0406506C:lib(4):func(101):reason(108)</p>
  
  <p>I tried various encoding and padding mode but always getting an error.</p>