Exemplo n.º 1
0
        /// <summary>
        /// 构造证书运行环境
        /// </summary>
        /// <param name="merchantCertPath">商户公钥证书路径</param>
        /// <param name="alipayCertPath">支付宝公钥证书路径</param>
        /// <param name="alipayRootCertPath">支付宝根证书路径</param>
        public CertEnvironment(string merchantCertPath, string alipayCertPath, string alipayRootCertPath)
        {
            if (string.IsNullOrEmpty(merchantCertPath) || string.IsNullOrEmpty(alipayCertPath) || string.IsNullOrEmpty(alipayCertPath))
            {
                throw new Exception("证书参数merchantCertPath、alipayCertPath或alipayRootCertPath设置不完整。");
            }

            this.RootCertContent = File.ReadAllText(alipayRootCertPath);
            this.RootCertSN      = AntCertificationUtil.GetRootCertSN(RootCertContent);

            X509Certificate merchantCert;

            if (merchantCertPath.StartsWith("cert:\\", StringComparison.OrdinalIgnoreCase))
            {
                merchantCert = GetPublicKeyFromCertificateStore(merchantCertPath);
            }
            else
            {
                merchantCert = AntCertificationUtil.ParseCert(File.ReadAllText(merchantCertPath));
            }
            this.MerchantCertSN = AntCertificationUtil.GetCertSN(merchantCert);

            X509Certificate alipayCert      = AntCertificationUtil.ParseCert(File.ReadAllText(alipayCertPath));
            string          alipayCertSN    = AntCertificationUtil.GetCertSN(alipayCert);
            string          alipayPublicKey = AntCertificationUtil.ExtractPemPublicKeyFromCert(alipayCert);

            CachedAlipayPublicKey[alipayCertSN] = alipayPublicKey;
        }
Exemplo n.º 2
0
        public void should_return_correct_pem_public_key_from_sm2_cert()
        {
            X509Certificate cert      = AntCertificationUtil.ParseCert(SM2AppCert);
            string          publicKey = AntCertificationUtil.ExtractPemPublicKeyFromCert(cert);

            Assert.AreEqual(publicKey, "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAERPDnzgyn7LI1wMyKHFrLTfxbVG2+hoDbZuy30ykrh1N50moR5GQecxXABpd6hRkPOENj+tuMQL8f3gJzcBl7sg==");
        }
Exemplo n.º 3
0
        public void should_return_correct_pem_public_key_from_rsa_cert()
        {
            string          certContent  = File.ReadAllText(TestAccount.ProdCert.CertParams.AlipayPublicCertPath);
            X509Certificate cert         = AntCertificationUtil.ParseCert(certContent);
            string          pemPublicKey = AntCertificationUtil.ExtractPemPublicKeyFromCert(cert);

            Assert.AreEqual(pemPublicKey, @"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0MYezLBe27D8kJU6CVjj5Zhn6lHq2SNqNu9uS1Kq2mxmDmgIMWvDgJurBV6Kuk8pEZbSARJgI2IzGLnUHpcMUr/DYUNXixBa2O6Nmd00PsvJb5S5r6lpxDMzqquBXFDeoM3dZ4rLBlbc1JJsfRKwfvPYOlgCldWxQmQUByI83zCKnGZHXVGeEopLDCgf53ChTiTyX9glCIt9VEZ8t1pSKAuOIxtUol9rDynW5G7EhkHA3xiKTUUATScZV1//GPA+0axQlh7Y4eDjUjE9vfsY0vBzTNIEkdsuECl8kbqV6zWPck07ZD4UCBI30o7ED57jPt2+1RXdxkg3A277JDUTSwIDAQAB");
        }
Exemplo n.º 4
0
        private async Task <string> LoadAlipayPublicKeyAsync(CertItem certItem, AlipayOptions options)
        {
            //为空时添加默认支付宝公钥证书密钥
            if (_certificateManager.IsEmpty)
            {
                _certificateManager.TryAdd(options.AlipayPublicCertSN, options.AlipayPublicCertKey);
            }

            //如果响应的支付宝公钥证书序号已经缓存过,则直接使用缓存的公钥
            if (_certificateManager.TryGet(certItem.CertSN, out var publicKey))
            {
                return(publicKey);
            }

            //否则重新下载新的支付宝公钥证书并更新缓存
            var request = new AlipayOpenAppAlipaycertDownloadRequest
            {
                BizContent = "{\"alipay_cert_sn\":\"" + certItem.CertSN + "\"}"
            };

            var response = await CertificateExecuteAsync(request, options);

            if (response.IsError)
            {
                throw new AlipayException("支付宝公钥证书校验失败,请确认是否为支付宝签发的有效公钥证书");
            }

            var alipayCertBase64  = response.AlipayCertContent;
            var alipayCertBytes   = Convert.FromBase64String(alipayCertBase64);
            var alipayCertContent = Encoding.UTF8.GetString(alipayCertBytes);

            if (!AntCertificationUtil.IsTrusted(alipayCertContent, options.RootCert))
            {
                throw new AlipayException("支付宝公钥证书校验失败,请确认是否为支付宝签发的有效公钥证书");
            }

            var alipayCert         = AntCertificationUtil.ParseCert(alipayCertContent);
            var alipayCertSN       = AntCertificationUtil.GetCertSN(alipayCert);
            var newAlipayPublicKey = AntCertificationUtil.ExtractPemPublicKeyFromCert(alipayCert);

            _certificateManager.TryAdd(alipayCertSN, newAlipayPublicKey);

            return(newAlipayPublicKey);
        }
Exemplo n.º 5
0
        /// <summary>
        /// 构造证书运行环境
        /// </summary>
        /// <param name="merchantCertPath">商户公钥证书路径</param>
        /// <param name="alipayCertPath">支付宝公钥证书路径</param>
        /// <param name="alipayRootCertPath">支付宝根证书路径</param>
        public CertEnvironment(string merchantCertPath, string alipayCertPath, string alipayRootCertPath)
        {
            if (string.IsNullOrEmpty(merchantCertPath) || string.IsNullOrEmpty(alipayCertPath) || string.IsNullOrEmpty(alipayCertPath))
            {
                throw new Exception("证书参数merchantCertPath、alipayCertPath或alipayRootCertPath设置不完整。");
            }

            this.RootCertContent = File.ReadAllText(alipayRootCertPath);
            this.RootCertSN      = AntCertificationUtil.GetRootCertSN(RootCertContent);

            X509Certificate merchantCert = AntCertificationUtil.ParseCert(File.ReadAllText(merchantCertPath));

            this.MerchantCertSN = AntCertificationUtil.GetCertSN(merchantCert);

            X509Certificate alipayCert      = AntCertificationUtil.ParseCert(File.ReadAllText(alipayCertPath));
            string          alipayCertSN    = AntCertificationUtil.GetCertSN(alipayCert);
            string          alipayPublicKey = AntCertificationUtil.ExtractPemPublicKeyFromCert(alipayCert);

            CachedAlipayPublicKey[alipayCertSN] = alipayPublicKey;
        }
Exemplo n.º 6
0
        private String LoadAlipayPublicKey(CertItem certItem)
        {
            //如果响应的支付宝公钥证书序号已经缓存过,则直接使用缓存的公钥
            if (certEnvironment.ContainsAlipayPublicKey(certItem.CertSN))
            {
                return(certEnvironment.GetAlipayPublicKey(certItem.CertSN));
            }

            //否则重新下载新的支付宝公钥证书并更新缓存
            AlipayOpenAppAlipaycertDownloadRequest request = new AlipayOpenAppAlipaycertDownloadRequest
            {
                BizContent = "{\"alipay_cert_sn\":\"" + certItem.CertSN + "\"}"
            };
            AlipayOpenAppAlipaycertDownloadResponse response = CertificateExecute(request);

            if (response.IsError)
            {
                throw new AopException("支付宝公钥证书校验失败,请确认是否为支付宝签发的有效公钥证书");
            }
            string alipayCertBase64 = response.AlipayCertContent;

            byte[] alipayCertBytes   = Convert.FromBase64String(alipayCertBase64);
            string alipayCertContent = Encoding.UTF8.GetString(alipayCertBytes);

            if (!AntCertificationUtil.IsTrusted(alipayCertContent, certEnvironment.RootCertContent))
            {
                throw new AopException("支付宝公钥证书校验失败,请确认是否为支付宝签发的有效公钥证书");
            }

            X509Certificate alipayCert         = AntCertificationUtil.ParseCert(alipayCertContent);
            String          alipayCertSN       = AntCertificationUtil.GetCertSN(alipayCert);
            string          newAlipayPublicKey = AntCertificationUtil.ExtractPemPublicKeyFromCert(alipayCert);

            certEnvironment.AddNewAlipayPublicKey(alipayCertSN, newAlipayPublicKey);

            return(newAlipayPublicKey);
        }
Exemplo n.º 7
0
        private async Task CheckResponseCertSignAsync <T>(IAlipayRequest <T> request, string responseBody, bool isError, IAlipayParser <T> parser, AlipayOptions options) where T : AlipayResponse
        {
            var certItem = parser.GetCertItem(request, responseBody);

            if (certItem == null)
            {
                throw new AlipayException("cert check fail: Body is Empty!");
            }

            if (!string.IsNullOrEmpty(certItem.CertSN))
            {
                // 为空时添加本地支付宝公钥证书密钥
                if (_alipayPublicKeyManager.IsEmpty)
                {
                    _alipayPublicKeyManager.TryAdd(options.AlipayPublicCertSN, options.AlipayPublicKey);
                }

                // 如果返回的支付宝公钥证书序列号与本地支付宝公钥证书序列号不匹配,通过返回的支付宝公钥证书序列号去网关拉取新的支付宝公钥证书
                if (!_alipayPublicKeyManager.ContainsKey(certItem.CertSN))
                {
                    var model = new AlipayOpenAppAlipaycertDownloadModel
                    {
                        AlipayCertSn = certItem.CertSN
                    };

                    var req = new AlipayOpenAppAlipaycertDownloadRequest();
                    req.SetBizModel(model);

                    var response = await CertificateExecuteAsync(req, options);

                    if (response.IsError)
                    {
                        throw new AlipayException("支付宝公钥证书校验失败,请确认是否为支付宝签发的有效公钥证书");
                    }

                    if (!AntCertificationUtil.IsTrusted(response.AlipayCertContent, options.RootCert))
                    {
                        throw new AlipayException("支付宝公钥证书校验失败,请确认是否为支付宝签发的有效公钥证书");
                    }

                    var alipayCert          = AntCertificationUtil.ParseCert(response.AlipayCertContent);
                    var alipayCertSN        = AntCertificationUtil.GetCertSN(alipayCert);
                    var alipayCertPublicKey = AntCertificationUtil.ExtractPemPublicKeyFromCert(alipayCert);

                    _alipayPublicKeyManager.TryAdd(alipayCertSN, alipayCertPublicKey);
                }

                // 针对成功结果且有支付宝公钥的进行验签
                if (_alipayPublicKeyManager.TryGetValue(certItem.CertSN, out var alipayPublicKey))
                {
                    if (!isError || isError && !string.IsNullOrEmpty(certItem.Sign))
                    {
                        var rsaCheckContent = AlipaySignature.RSACheckContent(certItem.SignSourceDate, certItem.Sign, alipayPublicKey, options.Charset, options.SignType);
                        if (!rsaCheckContent)
                        {
                            // 针对JSON \/问题,替换/后再尝试做一次验证
                            if (!string.IsNullOrEmpty(certItem.SignSourceDate) && certItem.SignSourceDate.Contains("\\/"))
                            {
                                var srouceData = certItem.SignSourceDate.Replace("\\/", "/");
                                var jsonCheck  = AlipaySignature.RSACheckContent(srouceData, certItem.Sign, alipayPublicKey, options.Charset, options.SignType);
                                if (!jsonCheck)
                                {
                                    throw new AlipayException("cert check fail: check Cert and Data Fail JSON also");
                                }
                            }
                            else
                            {
                                throw new AlipayException("cert check fail: check Cert and Data Fail!");
                            }
                        }
                    }
                }
                else
                {
                    throw new AlipayException("cert check fail: check Cert and Data Fail! CertSN non-existent");
                }
            }
        }