腾讯云AI开放平台sign签名算法(C#版)

腾讯云AI开放平台sign签名算法,网上没找到C#版的,自己参照例子写了个,直接上代码:

    static void Main(string[] args)
    {
        string app_id = "10000";
        string time_stamp = "1493449657";
        string nonce_str = "20e3408a79";
        string key1 = "腾讯AI开放平台";
        string key2 = "示例仅供参考";
        string app_key = "a95eceb1ac8c24ee28b70f7dbba912bf";
        Console.WriteLine(getReqSign(app_id,time_stamp,nonce_str,key1,key2,app_key));
        Console.ReadLine();
    }
    public static string getReqSign(string app_id,string time_stamp,string nonce_str,string key1,string key2,string app_key)
    {
        Dictionary<string, string> dic = new Dictionary<string, string>();
        dic.Add("app_id", app_id);
        dic.Add("time_stamp", time_stamp);
        dic.Add("nonce_str", nonce_str);
        dic.Add("key1", key1);
        dic.Add("key2", key2);
        dic.Add("sign", "");

        //字典升序
        dic = dic.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);

        //拼接按URL键值对
        string str = string.Empty;
        foreach (KeyValuePair<string,string> item in dic)
        {
            if (!string.IsNullOrEmpty(item.Value))
            {
                if (item.Key.Equals("nonce_str"))
                {
                    //注意nonce_str的值不能大写,否则sign签名值不对
                    str += item.Key + "=" + System.Web.HttpUtility.UrlEncode(item.Value) + "&";
                }
                else
                {
                    //注意其它URL键值必须大写,否则sign签名值不对
                    str += item.Key + "=" + System.Web.HttpUtility.UrlEncode(item.Value).ToUpper() + "&";
                }
            }
        }
        

        //拼接app_key
        str = str + "app_key="+app_key;

        // MD5运算+转换大写,得到请求签名
        MD5 mD5 = MD5.Create();
        //string str = "app_id=10000&key1=%E8%85%BE%E8%AE%AFAI%E5%BC%80%E6%94%BE%E5%B9%B3%E5%8F%B0&key2=%E7%A4%BA%E4%BE%8B%E4%BB%85%E4%BE%9B%E5%8F%82%E8%80%83&nonce_str=20e3408a79&time_stamp=1493449657&app_key=a95eceb1ac8c24ee28b70f7dbba912bf";
        byte[] bytes = UTF8Encoding.UTF8.GetBytes(str);
        byte[] sign  = mD5.ComputeHash(bytes);
        string signstr = string.Empty;
        foreach (byte item in sign)
        {
            signstr += item.ToString("X2");
        }
        return signstr.ToUpper();
    }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值