title: CNG Import ECC Pub/Priv Keyfrom file
body: <p>I've been trying to find how to import an ECC key from a file by ANY MEANS for ages. I have tried accessing an ECC cert from the Windows certificate store, from a .p12 file, and from a PKCS#8 OpenSSL key file with no success. </p>
  
  <p>Just one of the many things I have tried is:</p>
  
  <pre><code>StreamReader fs = new StreamReader("key.pem");
  String key = fs.ReadToEnd();
  byte[] tempkey = System.Text.Encoding.ASCII.GetBytes(key);
  CngKey cngKey = CngKey.Import(tempkey, CngKeyBlobFormat.Pkcs8PrivateBlob);
  </code></pre>
  
  <p>But no discriptive error messages are given, only that the last line either has <code>invalid parameters</code> or in the case of the code above <code>An error occurred during encode or decode operation.</code></p>
  
  <p>I am using the <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.ecdiffiehellmancng.aspx" rel="noreferrer">sample program</a> from MSDN for ECDH and <a href="http://blogs.msdn.com/b/shawnfa/archive/2009/03/17/authenticated-symmetric-encryption-in-net.aspx" rel="noreferrer">altered it</a> to use the GCM mode of AES. All of this works fine until I try and use pre-generated ECC keys instead of the ones created by default at runtime for the Microsoft example. I have randomly tried all of the <code>CngKeyBlobFormat</code>s but to be honest, I can't debug it very well because I don't know what those specific formats look like in raw data.</p>
  
  <p>My key is in the following format however I am willing to use any format that will work (.p12, Microsoft Store, PKCS#8, etc.)</p>
  
  <p><strong>key.pem</strong></p>
  
  <pre><code>-----BEGIN EC PARAMETERS-----
  ##############################
  -----END EC PARAMETERS-----
  -----BEGIN EC PRIVATE KEY-----
  ##############################
  -----END EC PRIVATE KEY-----
  </code></pre>
  
  <p><strong>Resources</strong></p>
  
  <p><a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.ecdiffiehellmancng.aspx" rel="noreferrer">MSDN API and Example: ECDiffieHellmanCng Class</a> </p>
  
  <p><a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.cngkey.aspx" rel="noreferrer">MSDN API: CngKey Class</a> </p>
  
  <p><a href="http://blogs.msdn.com/b/shawnfa/archive/2009/03/17/authenticated-symmetric-encryption-in-net.aspx" rel="noreferrer">MSDN Blogs: AES GCM Mode</a> </p>
  
  <p><a href="http://fixunix.com/openssl/159733-re-ecdsa-224-bit.html" rel="noreferrer">OpenSSL - Creating ECC keys</a> </p>