sign签名,md5加密,json序列化实例

23 篇文章 1 订阅

using System;
using System.Collections.Generic;
using System.Text;
using XingcOpen.ILS.Business.Config;
using XingcOpen.ILS.Business.Config.Module;
using XingcOpen.ILS.Business.Interface;
using XingcOpen.ILS.Core.Model;
using XingcOpen.ILS.Core.Log;
using System.Linq;
using System.Net;
using System.IO;
using System.Web;
using System.Security.Cryptography;
using XingcOpen.ILS.Core.Json;

namespace XingcOpen.ILS.Business.ExpressSystemApi.Client
{
///
/// 系统接口
///
class WDTExterpriseEdition : ISendPackageInfo
{
///
/// 取配置文件相关参数
///
private UserConfigInfo config = UserConfigHelper.GetInstance().userConfig;
Dictionary<string, string> requestParams = null;
private string appkey = “”;//客户提供
private string sid = “”;//客户提供
private string appsecret = “”;//加密appsecret,客户提供
private string url = “”;//请求地址

    public WDTExterpriseEdition()
    {
        appkey = config.kxApp_key;
        sid = config.sid;
        appsecret = config.kxApp_secret;
        url = config.HttpPostApiAddr;
    }

    /// <summary>
    /// 定义时间戳
    /// </summary>
    private string TICKS_DIFF()
    {
        TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        return Convert.ToInt64(ts.TotalSeconds).ToString();
    }
    bool ISendPackageInfo.CheckProcessHasRun()
    {
        throw new NotImplementedException();
    }

    bool ISendPackageInfo.CheckTicketNumHasEffective(string ticketsNum)
    {
        throw new NotImplementedException();
    }

    CommonResult ISendPackageInfo.GeneralSendTicketsNumAndPackageWeight(TicketInfo info)
    {
        throw new NotImplementedException();
    }

    public bool SendTicketsNumAndPackageWeight(string barcode, double weight, double length, double width, double height, double volume)
    {
        bool code = false;
        try
        {
            code = WeightResult(barcode, weight);
            Logger<WDTExterpriseEdition>.Debug("步骤已执行到1节点!" +code);

        }
        catch (Exception ex)
        {
            Logger<WDTExterpriseEdition>.Error("重量回传异常" + ex.Message);
         
        }
        return code;
    }

    T ISendPackageInfo.SendTicketsNumAndPackageWeight<T>(Dictionary<string, object> packageDic)
    {
        throw new NotImplementedException();
    }
    /// <summary>
    /// 重量回传
    /// </summary>
    public bool WeightResult(string barcode, double Weight)
    {
        try
        {
            requestParams = new Dictionary<string, string>();
            requestParams.Add("logistics_no", barcode);
            requestParams.Add("weight", Weight.ToString("f0"));
            string result = wdtOpenapi();
            Logger<WDTExterpriseEdition>.Debug("重量回传返回信息" + result);
            //序列化
            CodeResult codeResult = JsonHelper.JSONToObject<CodeResult>(result);

            if (codeResult.Code == 0)
            {
                //成功提示
                Logger<WDTExterpriseEdition>.Debug("WeightResult---重量回传成功!");
                return true;
            }
            else {
                Logger<WDTExterpriseEdition>.Debug("WeightResult---重量回传失败!当前codeResult.code的值为"+codeResult.Code);
            }
        }
        catch (Exception e)
        {
            Logger<WDTExterpriseEdition>.Error("WeightResult---重量回传数据异常:" + e.Message);
        }
        return false;
    }


    public string wdtOpenapi()
    {
        HttpWebRequest request = null;
        HttpWebResponse response = null;
        Stream serviceRequestBodyStream = null;
        try
        {
            request = (HttpWebRequest)WebRequest.Create(url);
            request.Credentials = CredentialCache.DefaultCredentials;
            request.KeepAlive = false;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
          
            UTF8Encoding encoding = new UTF8Encoding();

            requestParams.Add("appkey", appkey);
            requestParams.Add("sid", sid);
            requestParams.Add("timestamp", TICKS_DIFF());
            string sign = "";
            string postData = CreateParam(ref sign,true);
            Logger<WDTExterpriseEdition>.Debug("当前sign返回值为" + sign);
            byte[] bodyBytes = encoding.GetBytes(postData);
            request.ContentLength = bodyBytes.Length;
            using (serviceRequestBodyStream = request.GetRequestStream())
            {
                serviceRequestBodyStream.Write(bodyBytes, 0, bodyBytes.Length);
                serviceRequestBodyStream.Close();
                using (response = (HttpWebResponse)request.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        string result = reader.ReadToEnd();
                        reader.Close();
                        Logger<WDTExterpriseEdition>.Debug("Result输出值:"+result);
                        return result;
                    }
                   
                }
            }
        }
        catch (Exception ex)
        {
            Logger<WDTExterpriseEdition>.Debug("异常"+ex.Message);
            throw;
        }
        finally
        {
            if (response != null)
            {
                response.Close();
            }
            if (request != null)
            {
                request.Abort();
            }
        }
    }



    private string CreateParam(ref string sign,bool isLower = false)
    {
        //排序
        requestParams = requestParams.OrderBy(r => r.Key).ToDictionary(r => r.Key, r => r.Value);

        StringBuilder sb = new StringBuilder();
        int i = 0;
        foreach (var item in requestParams)
        {
            if (item.Key == "sign")
                continue;
            if (i > 0)
            {
                sb.Append(";");
            }
            i++;
            sb.Append(item.Key.Length.ToString("00"));
            sb.Append("-");
            sb.Append(item.Key);
            sb.Append(":");

            sb.Append(item.Value.Length.ToString("0000"));
            sb.Append("-");
            sb.Append(item.Value);
        }
        if (isLower)
            requestParams.Add("sign", MD5Encrypt(sb + appsecret).ToLower());
        else
        {
            requestParams.Add("sign", MD5Encrypt(sb + appsecret));
        }
        // 将计算得到的签名赋值给引用
        sign = requestParams["sign"];

        sb = new StringBuilder();
        i = 0;
        foreach (var item in requestParams)
        {
            if (i == 0)
                sb.Append(string.Format("{0}={1}", item.Key, HttpUtility.UrlEncode(item.Value, Encoding.UTF8)));
            else
                sb.Append(string.Format("&{0}={1}", item.Key, HttpUtility.UrlEncode(item.Value, Encoding.UTF8)));
            i++;
        }
        
        return sb.ToString();
       
    }

    private string MD5Encrypt(string strText)
    {
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] result = md5.ComputeHash(Encoding.UTF8.GetBytes(strText));
        string strMd5 = BitConverter.ToString(result);
        strMd5 = strMd5.Replace("-", "");
        return strMd5;// System.Text.Encoding.Default.GetString(result);
    }

    /// <summary>
    /// 响应参数
    /// </summary>
    private class CodeResult
    {

        /// <summary>
        /// 返回值,0:成功,其他失败
        /// </summary>
        public int Code { get; set; }
        /// <summary>
        /// 错误描述
        /// </summary>
        public string Message { get; set; }
    }
}

}

在C#中,快递100的Sign签名MD5加密通常用于身份验证过程中,需要对请求数据进行某种形式的安全处理。以下是基本步骤: 1. **收集数据**:首先,你需要获取到包含订单信息等必要字段的数据,例如`accessKey`、`orderNo`、`amount`等。 2. **拼接字符串(串接所有参数并按照特定顺序)**:将这些关键字段按照固定的顺序组合成一个字符串,通常会包括访问密钥(accessKey)、交易编号(orderNo),以及其他需要签名的数据。 示例: ```csharp string str = "accessKey=" + accessKey + "&orderNo=" + orderNo + "&amount=" + amount; ``` 3. **添加时间戳**:为了防止重放攻击,有时还会加入当前的时间戳或其他类似变量。 4. **MD5加密**:然后使用`System.Security.Cryptography.MD5`类对上述拼接后的字符串进行哈希运算。将字符串转换为字节数组,接着进行MD5加密。 示例: ```csharp MD5 md5 = MD5.Create(); byte[] hashBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(str)); ``` 5. **Base64编码**:由于HTTP请求头通常接受的是Base64编码的值,所以需要将加密后的字节数组转化为Base64字符串。 示例: ```csharp string sign = Convert.ToBase64String(hashBytes); ``` 6. **生成最终的Sign**:将时间戳、原始数据和加密后的MD5值再次组合,形成最终的Sign值,这个值会在API请求头中发送。 记得每次请求都要使用新的时间戳,因为MD5是不可逆的,这增加了安全性。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值