Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure Key Vault: unable to get a cert from kv when deployed

I have a webjob getting a certificate from azure key vault service and locally i have no problem accessing/retrieving this cert from kv. However, when this webjob gets deployed, I get this error:

System.Security.Cryptography.CryptographicException: The system cannot find the file specified.

   at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
   at System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromBlob(Byte[] rawData, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx)
   at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob(Byte[] rawData, Object password, X509KeyStorageFlags keyStorageFlags)
   at Microsoft.Ambassadors.Infrastructure.KeyVaultService.<GetCertificateAsync>d__7.MoveNext() in C:\Source\Repos\Xbox.Ambassadors\Microsoft.Ambassadors.Azure\Microsoft.Ambassadors.Infrastructure\KeyVaultService.cs:line 0

I have registered the app (where this webjob is hosted) with AAD, and it has read only access to the kv space. I have found a couple of relevant (I think..?) posts regarding this:

"An internal error occurred." when loading pfx file with X509Certificate2

X509Certificate Constructor Exception

but I'm not really sure if this is something that I can do in my case...? If anyone can help, that would really be great! Thanks :D

like image 400
Sahngah Lee Avatar asked Dec 24 '22 04:12

Sahngah Lee


1 Answers

I had this same problem, except I was deploying to an Azure web app. I fixed it by adding X509KeyStorageFlags.

SecretBundle secretBundle = await keyVaultClient.GetSecretAsync(_keyVaultOptions.IdentitySigningCredentialUri);
_signingCredential = new X509Certificate2(Convert.FromBase64String(secretBundle.Value), string.Empty, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
like image 165
Brian Redd Avatar answered Feb 15 '23 01:02

Brian Redd