首页 文章

创建X509Certificate2对象时,为什么会出现“拒绝访问”错误?

提问于
浏览
4

我们有一些单元测试,其中嵌入了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上的System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32hr)at System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromBlob(Byte [] rawData,IntPtr password,UInt32 dwFlags,Boolean persistKeySet,SafeCertContextHandle&pCertCtx) System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(Byte [] rawData)中的.X509Certificates.X509Certificate.LoadCertificateFromBlob(Byte [] rawData,Object password,X509KeyStorageFlags keyStorageFlags)

我已经尝试修改构造函数以使用空密码和显式键集标志,但这不能解决它:

// this doesn't work, either
return new X509Certificate2(bytes, String.Empty, X509KeyStorageFlags.MachineKeySet);

我在其他地方读过,我应该给我的非特权用户增加MachineKeys目录的权限,但我不喜欢这样做,因为它允许 生产环境 代码假设这些权限在测试环境之外的该目录上可用 .

Is there any way of allowing an unprivileged user to load an X509Certificate from a file?

2 回答

  • 5

    这是我对正在发生的事情的最好猜测 .

    X509Certificate2构造函数在Machine Keys目录中创建临时公钥/私钥对象(我相信通过Windows本地安全机构) . 由于我们的非特权用户无权访问这些密钥或Machine Keys目录,因此测试失败 .

    我们的解决方案是更新我们的环境设置脚本以提前安装这些测试证书,授予非特权用户权限,并重新编写测试以从相应的证书存储中加载证书 .

  • 4

    使用X509Certificate2构造函数中的“X509KeyStorageFlags.UserKeySet”标志帮助了我 .

相关问题