Beispiel #1
0
        public static void AddSign(HttpClient client, String signContent)
        {
            var sign = SignUtil.MakeSign(signContent, KeyConfig.Bill99YZTHehuaPrivateKey, PrivateKeyFormat.PKCS8, "RSA");

            if (sign.Success)
            {
                client.DefaultRequestHeaders.Remove("X-99Bill-Signature");
                client.DefaultRequestHeaders.Add("X-99Bill-Signature", sign.Value);
            }
        }
Beispiel #2
0
        private static void AddSign(HttpClient client, String interfaceUrl, String requestBody)
        {
            String requestId     = Guid.NewGuid().ToString("N");
            String timestamp     = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzzz");
            String version       = "yop-auth-v2";
            String expireSeconds = "1800";
            String appKey        = GlobalConfig.YeePay_FundOut_AppKey;

            var signHeaders = new SortedDictionary <String, String>();

            signHeaders["x-yop-appkey"]     = appKey;
            signHeaders["x-yop-request-id"] = requestId;
            signHeaders["x-yop-date"]       = timestamp;

            foreach (var key in signHeaders.Keys)
            {
                client.DefaultRequestHeaders.Remove(key);
                client.DefaultRequestHeaders.Add(key, signHeaders[key]);
            }

            //签名内容的请求头部分
            String signHeaderSignContent = String.Join("\n", signHeaders.Select(x => $"{WebUtil.UrlEncode(x.Key)}:{UrlEncodeToUpper(WebUtil.UrlEncode(x.Value))}"));

            //签名内容
            String signContent = $"{version}/{appKey}/{timestamp}/{expireSeconds}\nPOST\n{interfaceUrl}\n{requestBody}\n{signHeaderSignContent}";

            var sign = SignUtil.MakeSign(signContent, KeyConfig.YeePay_FundOut_Hehua_PrivateKey, PrivateKeyFormat.PKCS1, "RSA2");

            if (sign.Success)
            {
                String signHeaderNames   = String.Join(";", signHeaders.Keys);
                String base64SignContent = EncodeBase64(sign.Value) + "$SHA256";

                client.DefaultRequestHeaders.Remove("Authorization");
                String auth = GetAuthorization(version, appKey, timestamp, expireSeconds, signHeaderNames, base64SignContent);
                _logger.Debug($"Authorization={auth}");
                client.DefaultRequestHeaders.Add("Authorization", auth);
            }
        }
        public String Build(Action <XDocument> configAction = null)
        {
            String service = $"{this.GetType().FullName}.Build(...)";

            String xmlString = _serializer.Serialize(this.RequestBody, configAction);

            _logger.Trace(TraceType.BLL.ToString(), CallResultStatus.OK.ToString(), service, "xmlString", LogPhase.ACTION, "代付请求参数", xmlString);

            Byte[] xmlData = Encoding.UTF8.GetBytes(xmlString);

            //签名数据
            var signedResult = SignUtil.MakeSign(xmlData, KeyConfig.Bill99FOHehuaPrivateKey, PrivateKeyFormat.PKCS8, "RSA");

            if (!signedResult.Success)
            {
                _logger.Error(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, "signedResult", "生成签名数据失败", signedResult.FirstException, xmlString);
                return(null);
            }

            //密文
            var encryptedResult = CryptoHelper.AESEncrypt(xmlData, this.EncryptKey);

            if (!encryptedResult.Success)
            {
                _logger.Error(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, "encryptedResult", "生成密文失败", encryptedResult.FirstException, xmlString);
                return(null);
            }

            //数字信封
            var digResult = CryptoHelper.RSAEncrypt(this.EncryptKey, KeyConfig.Bill99FOPublicKey);

            if (!digResult.Success)
            {
                _logger.Error(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, "digResult", "生成数字信封失败", digResult.FirstException);
                return(null);
            }

            String signedData      = Convert.ToBase64String(signedResult.Value);
            String encryptedData   = Convert.ToBase64String(encryptedResult.Value);
            String digitalEnvelope = Convert.ToBase64String(digResult.Value);

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>");
            sb.Append($"<{this.RequestType}>");
            sb.Append($"<{this.RequestHead}>");
            sb.Append("<version>1.0</version>");
            sb.Append($"<memberCode>{GlobalConfig.X99bill_FundOut_Hehua_MemberCode}</memberCode>");
            //sb.Append($"<memberCode>10012138842</memberCode>");
            sb.Append($"</{this.RequestHead}>");
            sb.Append($"<{this.RequestBodyType}>");
            sb.Append("<sealDataType>");
            sb.Append($"<originalData></originalData>");
            sb.Append($"<signedData>{signedData}</signedData>");
            sb.Append($"<encryptedData>{encryptedData}</encryptedData>");
            sb.Append($"<digitalEnvelope>{digitalEnvelope}</digitalEnvelope>");
            sb.Append("</sealDataType>");
            sb.Append($"</{this.RequestBodyType}>");
            sb.Append($"</{this.RequestType}>");

            return(sb.ToString());
        }
Beispiel #4
0
        public static XResult <TResponse> Execute <TRequest, TResponse>(String interfaceUrl, TRequest request)
        {
            if (request == null)
            {
                return(new XResult <TResponse>(default(TResponse), new ArgumentNullException(nameof(request))));
            }

            String service = $"{typeof(Bill99UtilV1).FullName}.Execute(...)";

            var client = GetClient();

            var serializeResult = JsonUtil.SerializeObject(request);

            if (!serializeResult.Success)
            {
                return(new XResult <TResponse>(default(TResponse), serializeResult.FirstException));
            }

            String postBody = serializeResult.Value;

            _logger.Trace(TraceType.BLL.ToString(), CallResultStatus.OK.ToString(), service, "postBody", LogPhase.ACTION, "请求消息体明文", postBody);

            Byte[] postData = Encoding.UTF8.GetBytes(postBody);

            //签名数据
            var signedResult = SignUtil.MakeSign(postData, KeyConfig.Bill99_COE_v1_Hehua_PrivateKey, PrivateKeyFormat.PKCS8, "RSA");

            if (!signedResult.Success)
            {
                _logger.Error(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, "signedResult", "生成签名数据失败", signedResult.FirstException, postBody);
                return(null);
            }

            var encryptKey = CryptoHelper.GenerateRandomKey();

            //密文
            var encryptedResult = CryptoHelper.AESEncrypt(postData, encryptKey);

            if (!encryptedResult.Success)
            {
                _logger.Error(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, "encryptedResult", "生成密文失败", encryptedResult.FirstException, postBody);
                return(null);
            }

            //数字信封
            var digResult = CryptoHelper.RSAEncrypt(encryptKey, KeyConfig.Bill99_COE_v1_PublicKey);

            if (!digResult.Success)
            {
                _logger.Error(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, "digResult", "生成数字信封失败", digResult.FirstException);
                return(null);
            }

            var dic = new Dictionary <String, String>(3);

            dic["envelope"]      = Convert.ToBase64String(digResult.Value);
            dic["encryptedData"] = Convert.ToBase64String(encryptedResult.Value);
            dic["signature"]     = Convert.ToBase64String(signedResult.Value);

            String postJson = JsonUtil.SerializeObject(dic).Value;

            String requestUrl  = $"{ApiConfig.Bill99_COE_v1_RequestUrl}{interfaceUrl}";
            String traceMethod = $"{nameof(client)}.PostJson(...)";

            _logger.Trace(TraceType.UTIL.ToString(), CallResultStatus.OK.ToString(), service, traceMethod, LogPhase.BEGIN, "快钱COE:开始请求快钱COE接口", new Object[] { requestUrl, postJson });

            var result = client.PostJson(requestUrl, postJson);

            _logger.Trace(TraceType.UTIL.ToString(), (result.Success ? CallResultStatus.OK : CallResultStatus.ERROR).ToString(), service, traceMethod, LogPhase.ACTION, "快钱COE:结束请求快钱COE接口");

            if (!result.Success)
            {
                _logger.Error(TraceType.UTIL.ToString(), CallResultStatus.ERROR.ToString(), service, traceMethod, $"快钱COE:调用快钱COE接口失败:{result.ErrorMessage}", result.FirstException);
                return(new XResult <TResponse>(default(TResponse), result.FirstException));
            }

            if (result.Value == null)
            {
                _logger.Error(TraceType.UTIL.ToString(), CallResultStatus.ERROR.ToString(), service, traceMethod, $"快钱COE:调用快钱COE接口超时");
                return(new XResult <TResponse>(default(TResponse), ErrorCode.REQUEST_TIMEOUT));
            }

            try
            {
                String respString = result.Value.Content.ReadAsStringAsync().GetAwaiter().GetResult();

                _logger.Trace(TraceType.UTIL.ToString(), CallResultStatus.OK.ToString(), service, traceMethod, LogPhase.END, "快钱COE:快钱COE返回结果", respString);

                var decodeResponseResult = JsonUtil.DeserializeObject <Dictionary <String, String> >(respString);

                if (!decodeResponseResult.Success)
                {
                    return(new XResult <TResponse>(default(TResponse), ErrorCode.DESERIALIZE_FAILED, decodeResponseResult.FirstException));
                }

                var respDic = decodeResponseResult.Value;

                String envelope = respDic["envelope"];

                if (envelope.IsNullOrWhiteSpace())
                {
                    return(new XResult <TResponse>(default(TResponse), ErrorCode.INFO_NOT_EXIST, new ArgumentException($"快钱未返回{nameof(envelope)}字段")));
                }

                Byte[] digitalEnvData = null;
                try
                {
                    digitalEnvData = Convert.FromBase64String(envelope);
                }
                catch (Exception ex)
                {
                    return(new XResult <TResponse>(default(TResponse), ErrorCode.DECODE_FAILED, ex));
                }

                Byte[] key = null;
                using (var ms = new MemoryStream(digitalEnvData))
                {
                    var decryptKeyResult = CryptoHelper.RSADecrypt(ms, KeyConfig.Bill99_COE_v1_Hehua_PrivateKey, PrivateKeyFormat.PKCS8);
                    if (!decryptKeyResult.Success)
                    {
                        return(new XResult <TResponse>(default(TResponse), ErrorCode.DECRYPT_FAILED, decryptKeyResult.FirstException));
                    }

                    key = decryptKeyResult.Value;
                }

                String encryptedBase64String = respDic["encryptedData"];

                Byte[] encryptedData = null;
                try
                {
                    encryptedData = Convert.FromBase64String(encryptedBase64String);
                }
                catch (Exception ex)
                {
                    _logger.Error(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, "Convert.FromBase64String(...)", "encryptedData不是有效的Base64字符串");
                    return(new XResult <TResponse>(default(TResponse), ErrorCode.DECODE_FAILED, ex));
                }

                var decryptedResult = CryptoHelper.AESDecrypt(encryptedData, key);
                if (!decryptedResult.Success)
                {
                    return(new XResult <TResponse>(default(TResponse), ErrorCode.DECRYPT_FAILED, decryptedResult.FirstException));
                }

                String signBase64String = respDic["signature"];

                Byte[] sign = null;
                try
                {
                    sign = Convert.FromBase64String(signBase64String);
                }
                catch (Exception ex)
                {
                    _logger.Error(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, "Convert.FromBase64String(...)", "signedData不是有效的Base64字符串", ex);
                    return(new XResult <TResponse>(default(TResponse), ErrorCode.DECODE_FAILED, new RemoteException("signedData不是有效的Base64字符串")));
                }

                Byte[] signContent = decryptedResult.Value;

                var verifyResult = CryptoHelper.VerifySign(sign, signContent, KeyConfig.Bill99_COE_v1_PublicKey, HashAlgorithmName.SHA1);
                if (!verifyResult.Value)
                {
                    _logger.Error(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, "verifyResult", "快钱返回的数据验签失败", verifyResult.FirstException);
                    return(new XResult <TResponse>(default(TResponse), ErrorCode.SIGN_VERIFY_FAILED, new SignException("快钱返回的数据验签失败")));
                }

                try
                {
                    String decryptedValue = Encoding.UTF8.GetString(decryptedResult.Value);
                    _logger.Trace(TraceType.BLL.ToString(), CallResultStatus.OK.ToString(), service, nameof(decryptedValue), LogPhase.ACTION, "解密得到结果", decryptedValue);
                    return(JsonUtil.DeserializeObject <TResponse>(decryptedValue));
                }
                catch (Exception ex)
                {
                    return(new XResult <TResponse>(default(TResponse), ErrorCode.DECODE_FAILED, ex));
                }
            }
            catch (Exception ex)
            {
                return(new XResult <TResponse>(default(TResponse), ex));
            }
        }