title: RSA_public_decrypt failed
body: <p>I have created a demo program for</p>
  
  <pre><code>1) Generating RSA private and public key pair.
  2) RSA sign with private key and then using public key to for checking.
  But my RSA_public_decrypt  return -1;
  </code></pre>
  
  <p><strong>Code:</strong></p>
  
  <pre><code>#include &lt;memory&gt;
  
  #include &lt;openssl/bn.h&gt;
  #include &lt;openssl/rsa.h&gt;
  
  #include &lt;cassert&gt;
  #define ASSERT assert
  #include &lt;iostream&gt;
  
  using namespace std;
  
  
  int padding = RSA_PKCS1_PADDING;
  
  #define NONCE_LEN 32
  
  int main(int argc, char* argv[])
  {
  
      unsigned char  encrypted[4098]={};
      unsigned char decrypted[4098]={};
  
      uint8_t nonceB[NONCE_LEN]={"FGHIJKLMNOPQRSTUVWXYZ0123456789"};
      uint8_t nonceA[NONCE_LEN]={"yogendra singh the developer of"};
  
  
      uint8_t nonceRes[NONCE_LEN];
  
      int rc;
  
      BIGNUM *e = BN_new();
      rc = BN_set_word(e, RSA_F4);
  
      assert(rc==1);
  
      RSA *rsaKeyPair = RSA_new();
      rc = RSA_generate_key_ex(rsaKeyPair, 2048, e, NULL);
      ASSERT(rc ==1);
  
      RSA *privateKey = RSA_new();
      privateKey=  RSAPrivateKey_dup(rsaKeyPair);
  
      RSA *publicKey = RSA_new();
      publicKey= RSAPublicKey_dup(rsaKeyPair);
  
  
  
      for(int i;i&lt;NONCE_LEN;i++){
          nonceRes[i]=nonceA[i]^nonceB[i];
      }
  
  
  
      int result = RSA_private_encrypt(NONCE_LEN,nonceRes,encrypted,privateKey,padding);
      int result2 = RSA_public_decrypt(NONCE_LEN,encrypted,decrypted,publicKey,padding);
  
      cout&lt;&lt;"encrypted len:"&lt;&lt;result&lt;&lt;endl;
  
      RSA_free(privateKey);
      RSA_free(publicKey);
      BN_free(e);
  
      cout&lt;&lt;"decrypted len:"&lt;&lt;result2&lt;&lt;endl;
  
      cout&lt;&lt;endl &lt;&lt;"decoded String B:";
      for(int i =0;i&lt;NONCE_LEN;i++){
          char x=nonceB[i]^decrypted[i];
  
          cout&lt;&lt;x;
      }
  
  
      cout&lt;&lt;endl &lt;&lt;"decoded String A:";
      for(int i =0;i&lt;NONCE_LEN;i++){
          char x=nonceA[i]^decrypted[i];
  
          cout&lt;&lt;x;
      }
  
      cout&lt;&lt;endl;
      return 0;
  }
  </code></pre>
  
  <p><strong>Output:</strong> </p>
  
  <pre><code>encrypted len:256
  decrypted len:-1
  </code></pre>