We have several unit tests in which PFX certificates are embedded. These certificates are read at run time and converted to X509Certificate2 objects. Unfortunately, when starting as an unprivileged user, we get Access Denied exceptions:
using (var s = EmbeddedResourceUtilities.GetEmbeddedResourceAsStream(typeThatContainsEmbeddedResource, certFileName)) { if (s == null) { throw new ApplicationException(String.Format("Embedded certificate {0} for type {1} not found.", certFileName, typeThatContainsEmbeddedResource.FullName)); } try { var bytes = new byte[s.Length]; s.Read(bytes, 0, (int)s.Length); return new X509Certificate2(bytes); } catch (Exception ex) { throw new ApplicationException(String.Format("Error loading embedded certificate {0} for type {1}.", certFileName, typeThatContainsEmbeddedResource.FullName), ex); } }
Here's the exception:
System.Security.Cryptography.CryptographicException: Access denied.
at System.Security.Cryptography.CryptographicException.ThrowCryptographicException (Int32 hr)
in System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromBlob (Byte [] rawData, password IntPtr, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle & pCertCtx)
in System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob (Byte [] rawData, object password, X509KeyStorageFlags keyStorageFlags)
in System.Security.Cryptography.X509Certificates.X509Certificate2..ctor (Byte [] rawData)
I tried modifying the constructor to use an empty password and explicit set flags, but this does not fix it:
I read elsewhere that I should give my unprivileged users increased permissions in the MachineKeys directory, but I do not want to do this, as this will allow the production code to assume that these permissions are available in this directory outside the test environment.
Is there a way to allow an unprivileged user to load X509Certificate from a file?
source share