简体   繁体   中英

Azure Web Application new X509Certificate2() causing System.Security.Cryptography.CryptographicException: Access denied

Right now I am uploading a .pfx file, taking in a password and calling

var cert = new X509Certificate2(fileData, password);

And storing things like the thumbprint, etc. I do not need to actually store this on the server, just validate that it is a valid cert and store some information. On local this works (obviously I have better access to my key store) but when I put it up in azure I get the error:

System.Security.Cryptography.CryptographicException: Access denied.

Is there any way to get this information sidestepping this or to use this method without getting an access denied? I am not very good with certs, so let me know if you need more information. Thank you.

When opening a PFX on Windows any private keys get written to disk. They will get deleted later (unless you specify PersistKeySet), but they do still have to be written (ish).

Where are they written?

  • If you specify X509KeyStorageFlags.MachineKeySet : In the machine keystore, you need to be an administrator.
  • If you specify X509KeyStorageFlags.UserKeySet : In the user keystore, your user profile probably needs to exist/load.
  • If you don't specify either:
    • If the PFX itself has encoded that the key belongs in the machine key set, then the machine keystore (admin required).
    • Otherwise the user keystore (profile probably required).

Given "Access Denied" I'd guess that you hit the case where the PFX itself specified the machine keystore, to resolve this you'd change your call to

new X509Certificate2(fileData, password, X509KeyStorageFlags.UserKeySet)

and everything should work. If you specify UserKeySet and still get an error, that might a profile-loading problem.

There is an option to load a PFX without writing the private keys to disk, but it's not available in .NET Framework (though it was recently added to .NET Core). If you really need it you could look into p/invoking PFXImportCertStore with the PKCS12_NO_PERSIST_KEY flag, then pass the resultant HCERTSTORE value to X509Store.ctor(IntPtr) and read your certificate(s) via the X509Store.Certificates property. Note, though, that most of .NET Framework won't understand that these cert objects have associated private keys, so they'll likely only behave as public-only certificate objects.

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