Search code examples
c#.netcryptographyx509certificatex509certificate2

X509Certificate2.GetECDsaPrivateKey error keyHandle null value


I generated a pfx file with the following commands

openssl ec -in apple-private-key.pem -pubout -out apple-public-key.pem
openssl req -new -key apple-private-key.pem -x509 -nodes -subj "/CN=apple.my.com" -out certificat.pem
openssl pkcs12 -in certificat.pem -inkey apple-private-key.pem -export -out certificate.pfx

and when I try to load it only with the flag X509KeyStorageFlags.MachineKeySet this flag is necessary for me, for the execution on a windows server with IIS

// only if add MachineKeySet flag
var certificate = new X509Certificate2("apple-certificate.pfx", "password", X509KeyStorageFlags.MachineKeySet); 
var ecDsa = certificate.GetECDsaPrivateKey(); // <<   Error keyHandle Null ?
var key = new ECDsaSecurityKey(ecDsa) { KeyId = _keyId };
var signingCredentials = new SigningCredentials(key, "ES256", _keyId);

Error

System.ArgumentNullException
  HResult=0x80004003
  Message=La valeur ne peut pas être null.
Nom du paramètre : keyHandle
  Source=System.Core
  Arborescence des appels de procédure :
   à System.Security.Cryptography.CngKey.Open(SafeNCryptKeyHandle keyHandle, CngKeyHandleOpenOptions keyHandleOpenOptions)
   à System.Security.Cryptography.X509Certificates.ECDsaCertificateExtensions.GetECDsaPrivateKey(X509Certificate2 certificate) 

Solution

  • It must run with a local administrator account, for this to work.

    Thanks, Crypt32, jdweng

    https://paulstovell.com/x509certificate2/