title: C++ Importing RSA public keys from modulus and exponent with CNG
body: <p>I'm trying to use CNG to encrypt some data with a public key that is given as a parameter. When calling NCryptImportKey function, I get a NTE_BAD_DATA error <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa376276(v=vs.85).aspx" rel="nofollow noreferrer"> which isn't listed in the msdn page.</a></p>
  
  <p>My code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;Windows.h&gt;
  #include &lt;Bcrypt.h&gt;
  #include &lt;Ntstatus.h&gt;
  #include &lt;string&gt;
  #include &lt;vector&gt;
  #include "base64.h"
  
  using std::string;
  using std::vector;
  
  struct MyRSAPublicBlob {
      BCRYPT_RSAKEY_BLOB blob;
      BYTE exponent[3];
      BYTE modulus[128];
      MyRSAPublicBlob(const vector&lt;BYTE&gt;&amp; mod, const vector&lt;BYTE&gt;&amp; exp)
      {
          blob.BitLength = (128 + 3) * 8;
          blob.Magic = BCRYPT_RSAPUBLIC_MAGIC;
          blob.cbModulus = 128;
          blob.cbPublicExp = 3;
          for (size_t i = 0; i &lt; mod.size(); ++i) //copy BigEndian
              modulus[i] = mod[mod.size() - 1 - i];
          for (size_t i = 0; i &lt; exp.size(); ++i) //copy BigEndian
              exponent[i] = exp[exp.size() - 1 - i];
      }
      MyRSAPublicBlob() { ; }
  
  };
  
  MyRSAPublicBlob b;
  
  bool RSA_encrypt() {
      SECURITY_STATUS stat;
      NCRYPT_PROV_HANDLE hProv;
      NCRYPT_KEY_HANDLE hKey;
  
      stat = NCryptOpenStorageProvider(&amp;hProv, MS_KEY_STORAGE_PROVIDER, 0);
      if (ERROR_SUCCESS != stat) {
          std::cout &lt;&lt; "failed in NCryptOpenStorageProvider: " &lt;&lt; GetLastError() &lt;&lt; std::endl;
          return false;
      }
      stat = NCryptImportKey(hProv,
          NULL,
          BCRYPT_RSAPUBLIC_BLOB,
          NULL,
          &amp;hKey,
          (PBYTE)&amp;b.blob,
          sizeof(b),
          0);
  
      if (ERROR_SUCCESS != stat) {
          std::cout &lt;&lt; "failed in NCryptImportKey: " &lt;&lt; GetLastError() &lt;&lt; std::endl;
          return false;
      }
  </code></pre>
  
  <p>Example of how I construct MyRSAPublicBlob:</p>
  
  <pre><code>string PubKeyModulus = "yVUndgQFuB5Z5FgC0/WgWCg6Y8VuB582avGjQDdeoJDa1+RBKCyXo700sAMSGjM/bVakOlFqvCsVFNBysx1CH731CDb2DR1a0bsmYmDQ9d0ZHX+AOohVDIx9mc7bkDQZoEFpe9NqFsu95Y9yktpl1JKPmKyLOFgufGJYYvQyoOM=";
  string PubKeyExp = "AQAB";
  
  vector&lt;BYTE&gt; PubKeyModulus_bin = base64_decode(PubKeyModulus);
  vector&lt;BYTE&gt; PubKeyExp_bin = base64_decode(PubKeyExp);
  struct MyRSAPublicBlob c(PubKeyModulus_bin, PubKeyExp_bin);
  b = c;
  </code></pre>
  
  <p>Anything I'm doing bluntly wrong?</p>