我们有一些单元测试,其中嵌入了 PFX 证书。这些证书在测试执行期间被读取并变成X509Certificate2
对象。不幸的是,当以非特权用户身份运行时,我们会遇到Access Denied
异常:
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);
}
}
这是一个例外:
System.Security.Cryptography.CryptographicException:访问被拒绝。
在 System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
在 System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromBlob(Byte[] rawData, IntPtr 密码, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx)
在 System.Security.Cryptography .X509Certificates.X509Certificate.LoadCertificateFromBlob(Byte[] rawData, Object password, X509KeyStorageFlags keyStorageFlags)
在 System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(Byte[] rawData)
我尝试修改构造函数以使用空密码和显式键集标志,但这并不能解决它:
// this doesn't work, either
return new X509Certificate2(bytes, String.Empty, X509KeyStorageFlags.MachineKeySet);
我在其他地方读到我应该给我的非特权用户增加对 MachineKeys 目录的权限,但我不愿意这样做,因为它会允许生产代码假设这些权限在测试环境之外的那个目录上可用。
有没有办法允许非特权用户从文件中加载 X509Certificate?