Failed to access my X509Certificate2 PrivateKey In Azure

I have my own X509Certificate stored in the database (in byte[] ) so that my application can receive the certificate and use it to sign my JWT.

My x509Certificate is transferred from the .pfx file that I generated on my computer, however now it is in the database as a string of bytes.

My application works fine locally when I run it. An application can correctly create an instance of this X509Certificate2 and use it for my requirements, however, the problem occurs when I try to use it in my azurewebsites web application.

Basically, I cannot access the privateKey instance variable of the certificate, I get an exception

 System.Security.Cryptography.CryptographicException: Keyset does not exist 

And I re-create the certificate using this

 var cert = new X509Certificate2(myCertInBytes, myCertPass, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable); 

I am using ASPNET 5 rc1-update1. I also tried running this on another machine, and it works fine, only this problem occurs when publishing to Azure. And also add something else. This application worked when I ran the same project that was running using the DNX beta7 version

Any help was appreciated.

+8
asp.net-core azure x509 certificate azure-web-sites
source share
1 answer

The problem is that Azure Web Apps restricts access to the private key store of the machines, as it is a collaborative environment and you do not own the machine completely. As a workaround, you can download the certificate. This blog post describes best practices for how to do this: https://azure.microsoft.com/en-us/blog/using-certificates-in-azure-websites-applications/

Please note that this only works for the basic level and higher (not for the free or general level).

You can also do this from the .cer file as follows, however, it should be noted that these are not best practices, since you keep secure credentials with the code in an insecure format.

 public X509Certificate2 CertificateFromStrings(String certificateString64, String privateKeyXml) { try { var rsaCryptoServiceProvider = new RSACryptoServiceProvider(); rsaCryptoServiceProvider.FromXmlString(privateKeyXml); var certificateBytes = Convert.FromBase64String(certificateString64); var x509Certificate2 = new X509Certificate2(certificateBytes); x509Certificate2.PrivateKey = rsaCryptoServiceProvider; return x509Certificate2; } catch { return null; } } 
+6
source share

All Articles