【发布时间】:2013-02-23 11:15:42
【问题描述】:
我们有一些单元测试,其中嵌入了 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 小时)
在 System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromBlob(Byte[] rawData, IntPtr 密码, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx)
在 System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob(Byte[] rawData, 对象密码, 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?
【问题讨论】:
标签: .net x509certificate x509certificate2