简体   繁体   English

如何从X509证书初始化ECDiffieHellmanCngPublicKey

[英]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). 我想从X509证书的公共密钥初始化ECDiffieHellmanCngPublicKey(该证书是使用ECDH_P384模板颁发的)。 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. 最后一行抛出System.Security.Cryptography.CryptographicException:“与ECDiffieHellmanCng算法一起使用的密钥必须具有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 . 您提供的密钥类型是ECDSA公钥(BCRYPT_ECDSA_PUBLIC_P384_MAGIC),而不是ECDH公钥(BCRYPT_ECDH_PUBLIC_P384_MAGIC),如参考答案所示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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