【问题标题】:X509Certificate2 certification issueX509Certificate2 认证问题
【发布时间】:2020-05-25 20:04:13
【问题描述】:

我正在开发与相关机构提供的证书密钥 (.pfx) 文件的支付网关集成, 当我在 localhost 上工作时,一切都按我的预期完美运行。但是在我在 windows server 2019 中发布后,我们在令牌生成过程中遇到了一些问题。

这是我们使用的令牌生成代码

RSACng key = new System.Security.Cryptography.RSACng();
            X509Certificate2 publicCert = new X509Certificate2(publicKeyLocation, "123", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
            X509Certificate2 privateCert = null;
            X509Store store = new X509Store(StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly);
            foreach (X509Certificate2 cert in store.Certificates)
            {
                var val1 = publicCert.GetCertHashString();
                if (cert.GetCertHashString() == publicCert.GetCertHashString())
                    privateCert = cert;
            }
            key = privateCert.GetRSAPrivateKey() as RSACng;
            byte[] signature = key.SignHash(hashValue, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
            key = (System.Security.Cryptography.RSACng)publicCert.GetRSAPublicKey();
            if (!key.VerifyHash(hashValue, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1))
                throw new CryptographicException();
            return signature;

这是我们从 localhost

调用 api 时得到的响应

这是我们在windows server 2019发布后api的响应

【问题讨论】:

    标签: c# asp.net-web-api operating-system x509certificate2 windows-server-2019


    【解决方案1】:

    问题出在这里:X509Store store = new X509Store(StoreLocation.CurrentUser);

    这可以在您的 PC 上运行,因为您在 CurrentUser 存储下存储了证书,但是当您将应用程序部署到 Windows Server 时,运行应用程序的用户在其证书存储中没有特定的证书。

    将证书安装到 LocalMachine 证书存储并从那里获取:

    X509Store store = new X509Store(StoreLocation.LocalMachine);
    

    或安装证书以更正 CurrentUser 存储(不推荐,用户可能是 NetworkUser,或 System,...)

    【讨论】:

    • 感谢您的重播,在我更改代码并发布后,我得到了一些类似“密钥集不存在”的错误。我点击了这个链接stackoverflow.com/questions/12106011/…,最后问题是已解决。再次感谢@Tomas 解决此问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多