简体   繁体   中英

How to initialize ECDiffieHellmanCngPublicKey from an X509 Certificate

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM