.net - 为什么在创建 X509Certificate2 对象时会收到拒绝访问错误?

标签 .net x509certificate x509certificate2

我们有一些单元测试,其中嵌入了 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/

相关文章:

c# - 检查文件是否已在源代码管理中

.net - WinInet 如何确定缓存什么以及何时缓存?

android - 从android中的X509Certificate中提取组织名称

java - 如何在 Java Web 应用程序中实现基于 PKI 证书的身份验证

pki - C#以pfx格式导出证书

c# - 使用 X509Certificate2 找不到指定的对象

.net - 选择免费的安装程序产品并将下载/安装 .NET Framework

c# - 在列表中查找具有最低属性值的项目

certificate - 如何将PEM格式的X509证书和私钥转换为GPG格式?

powershell - 导入证书 - 访问被拒绝(以管理员身份运行时)