title: OpenSSL EVP_DigestSignFinal segfault
body: <p>I'm trying to sign a message using the OpenSSL C api.  The following code segfaults because of <code>EXC_BAD_ACCESS</code> during either of the calls to <code>EVP_DigestSignFinal</code>.  I'm using OpenSSL 1.0.1g.  I tried switching from the newer <code>DigestSign*</code> functions to the older <code>Sign*</code> functions, and it still segfaults.</p>
  
  <p><code>private_key</code> is set with <code>EVP_PKEY_set1_RSA</code> from an RSA key loaded from a PEM file.  The first call to <code>EVP_DigestSignFinal</code> fills <code>s_len</code> with the maximum possible length of the signature for the signing algorithm, so <code>signature</code> not being big enough shouldn't be the issue, and the second call writes to the signature buffer and fills <code>s_len</code> with the length of the signature.</p>
  
  <p>I would appreciate any help I could get with this.</p>
  
  <pre><code>vector&lt;unsigned char&gt; rsa_sha512_sign(
          const vector&lt;unsigned char&gt;&amp; document, 
          shared_ptr&lt;EVP_PKEY&gt; private_key) {
      EVP_MD_CTX* md;
      if (!(md = EVP_MD_CTX_create())) {
          throw runtime_error("Error initializing ENV_MD_CTX.");
      }
  
      if (EVP_DigestSignInit(md, NULL, EVP_sha512(), NULL, private_key.get()) 
              != 1) {
          throw runtime_error("Error in EVP_DigestSignInit.");
      }
  
      if (EVP_DigestSignUpdate(md, document.data(), document.size()) != 1) {
          throw runtime_error("Error computing hash on document.");
      }
      size_t s_len;
      if (EVP_DigestSignFinal(md, NULL, &amp;s_len) != 1) { // Segfault here
          throw runtime_error("Error determining maximum signature size.");
      }
  
      vector&lt;unsigned char&gt; signature(s_len);
      if (EVP_DigestSignFinal(md, signature.data(), &amp;s_len) != 1) { // or here (or both)
          throw runtime_error("Error signing document.");
      }
      signature.resize(s_len);
      EVP_MD_CTX_destroy(md);
      return move(signature);
  }
  </code></pre>