title: Get CryptoAPI public key via PKCS#11
body: <p>In my C++ program I created a public/private key pair using <strong>CryptoAPI</strong>.</p>
  
  <pre><code>CryptGenKey(eTokenProv,ENCRYPT_ALGORITHM,CRYPT_EXPORTABLE,&amp;k1)
  </code></pre>
  
  <p>Keys are stored in a <strong>eToken</strong>.
  Is it possible to get the public key using <strong>PKCS#11</strong>? The private key previously created is found after a search using the following search-template:</p>
  
  <pre><code>    CK_ATTRIBUTE private_search[] = {
         {CKA_PRIVATE, CK_TRUE, sizeof(CK_BBOOL)}
      };
  </code></pre>
  
  <p>If I set <code>CKA_PRIVATE</code> to CK_FALSE, I can't get the public key. I also tried with other attributes.
  Is there a way to do it?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>As <strong>owlstead</strong> suggests, I tried to create a public key starting from the modulus and public exponent of a key created in a previous session (in CAPI or, just for this test, in PKCS11). I got the modulus and public exponent from a private key in these buffers: </p>
  
  <pre><code>CK_BYTE  modulus[128]; //if 1024bit
  CK_BYTE  publicExponent[4]; //4 Byte, according to public key blob
  </code></pre>
  
  <p>But when I try to create a new public with key with the following instructions:</p>
  
  <pre><code>CK_ATTRIBUTE publicKeyTemplate[] = {
      {CKA_TOKEN, &amp;yes, sizeof(true)},
      {CKA_WRAP, &amp;yes, sizeof(true)},
      {CKA_ENCRYPT, &amp;yes, sizeof(true)},
      {CKA_MODULUS_BITS, &amp;modulusBits, sizeof(modulusBits)},
      {CKA_MODULUS, &amp;modulus, sizeof(modulus)},
      {CKA_PUBLIC_EXPONENT, &amp;publicExponent, sizeof(publicExponent)}
  
  CK_MECHANISM mechanism = {CKM_RSA_PKCS_KEY_PAIR_GEN, NULL_PTR, 0 };
  rv = (*functions-&gt;C_GenerateKeyPair) (session, &amp;mechanism, publicKeyTemplate, 6, privateKeyTemplate, 6, &amp;hPublicKey, &amp;hPrivateKey); 
  </code></pre>
  
  <p>I get the error "Invalid template". The probles is the modulus, because, without it, I can create a key pair. I use the function <code>C_GenerateKeyPair</code>, but I'm only interested in the public key. I omitted the private template.
  What is the wrong here?</p>