2

I would like to initialize ECDiffieHellmanCngPublicKey from a public key of an X509 certificate (the certificate was issued using ECDH_P384 template). Here is what I tried:

var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.OpenExistingOnly);
var cert = store.Certificates.Find(X509FindType.FindByTemplateName, "ComputerECC", true)[0];
var keyType = new byte[] { 0x45, 0x43, 0x53, 0x33 };
var keyLength = new byte[] { 0x30, 0x00, 0x00, 0x00 };
var key = cert.PublicKey.EncodedKeyValue.RawData.Skip(1);
var keyImport = keyType.Concat(keyLength).Concat(key).ToArray();
var pubKey = ECDiffieHellmanCngPublicKey.FromByteArray(keyImport, CngKeyBlobFormat.EccPublicBlob);

The last line throws System.Security.Cryptography.CryptographicException: "Keys used with the ECDiffieHellmanCng algorithm must have an algorithm group of ECDiffieHellman.

The idea of using the magic values to parse the key came from this question I suspect that something is missing in my certificate template.

Community
  • 1
  • 1
immutableT
  • 439
  • 4
  • 13
  • Tried this: private static ECDiffieHellmanPublicKey ImportEccPublicKeyFromCertificate(X509Certificate2 cert) { var keyType = new byte[] { 0x45, 0x43, 0x53, 0x33 }; var keyLength = new byte[] { 0x30, 0x00, 0x00, 0x00 }; var key = cert.PublicKey.EncodedKeyValue.RawData.Skip(1); var keyImport = keyType.Concat(keyLength).Concat(key).ToArray(); return ECDiffieHellmanCngPublicKey.FromByteArray(keyImport, CngKeyBlobFormat.EccPublicBlob); } – immutableT Mar 10 '16 at 01:57

1 Answers1

0

Nothing wrong with the template. The issue is actually with the Key Type.

var keyType = new byte[] { 0x45, 0x43, 0x53, 0x33 };

should actually be

var keyType = new byte[] { 0x45, 0x43, 0x4B, 0x33 };

The key type you provided was for an ECDSA public key (BCRYPT_ECDSA_PUBLIC_P384_MAGIC), not an ECDH public key (BCRYPT_ECDH_PUBLIC_P384_MAGIC), as shown in the referenced answer.

jproch
  • 301
  • 2
  • 13