我们有一些单元测试,其中嵌入了 PFX 证书。这些证书在测试执行期间被读取并转换为 X509Certificate2
对象。不幸的是,当以非特权用户身份运行时,我们得到 Access Denied
异常(exception):
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);
}
}
这是异常(exception):
System.Security.Cryptography.CryptographicException : Access denied.
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 System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(Byte[] rawData)
我尝试修改构造函数以使用空密码和显式 key 集标志,但这并不能解决问题:
// this doesn't work, either
return new X509Certificate2(bytes, String.Empty, X509KeyStorageFlags.MachineKeySet);
我在别处读到我应该给我的非特权用户增加对 MachineKeys 目录的权限,但我不愿意这样做,因为它会允许生产代码假设这些权限在测试环境之外的目录上可用。
有没有办法允许非特权用户从文件加载 X509Certificate?
最佳答案
在 X509Certificate2 构造函数中使用“X509KeyStorageFlags.UserKeySet”标志帮助了我。
关于.net - 为什么在创建 X509Certificate2 对象时会收到拒绝访问错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15285046/