通用 HTTP 簽名元件的另類實現

2022-09-27 06:06:35

1、初衷

開發中經常需要做一些介面的簽名生成和校驗工作,最開始的時候都是每個介面去按照約定單獨實現,久而久之就變的非常難維護,因此就琢磨怎麼能夠寫了一個比較通用的簽名生成工具。

2、思路

採用鏈式呼叫的方式,使得簽名的步驟可以動態拼湊組合。

3、直接看效果

    //設定資料來源
    var signSource = new Dictionary<string, string>()
    {
        { "param1", "1" },
        { "param3", "3+" },
        { "param2", "2" }
    };
    var signer = new HttpSigner();
    signer.SetSignData(signSource);

    //設定資料來源並設定規則
    signer.SetSignData(signSource, setting =>
    {
        //按引數名排序
        //result --> param1 param2 param3
        setting.IsOrderByWithKey = false;

        //是否對簽名資料的引數值進行UrlEncode
        setting.IsDoUrlEncodeForSourceValue = false;

        //簽名主體是否包含引數名
        setting.IsSignTextContainKey = true;
        //簽名主體中引數和引數值的連線符(需要啟用IsSignTextContainKey)
        setting.SignTextKeyValueSeparator = "=";
        //簽名主體中不同引數項的連線符
        setting.SignTextItemSeparator = "&";
        //以上都開啟後  --> param1=1&param2=2&param3=3

        //編碼
        setting.DefaultEncoding = Encoding.UTF8;
    });

    //簽名主體設定字首
    signer.SetSignData(signSource).SetSignTextPrefix("TestPrefix");

    //簽名主體設定字尾
    signer.SetSignData(signSource).SetSignTextSuffix("TestSuffix");

    //簽名主體進行Base64
    signer.SetSignData(signSource).SetSignTextBase64();

    //簽名主體進行MD5,(方法引數為簽名結果是否轉小寫)
    signer.SetSignData(signSource).SetSignTextMD5(bool isToLower = true);

    //簽名主體進行SHA1,(方法引數為簽名結果是否轉小寫)
    signer.SetSignData(signSource).SetSignTextSHA1(bool isToLower = true);

    //獲取簽名結果
    string signString = signer.SetSignData(signSource).GetSignResult();

    //組合呼叫
    string signString = signer.SetSignData(signSource).SetSignTextBase64().SetSignTextMD5().SetSignTextSHA1();

4、程式碼實現

HttpSignItem類

用於儲存簽名的引數集合。

namespace JiuLing.CommonLibs.Security.HttpSign
{
    internal class HttpSignItem
    {
        public string Key { get; set; }
        public string Value { get; set; }

        public HttpSignItem(string key, string value)
        {
            Key = key;
            Value = value;
        }
    }
}

HttpSignSetting類

用於簽名的基本設定。

using System.Text;

namespace JiuLing.CommonLibs.Security.HttpSign
{
    /// <summary>
    /// 簽名設定
    /// </summary>
    public class HttpSignSetting
    {
        /// <summary>
        /// 是否按引數名進行排序
        /// </summary>
        public bool IsOrderByWithKey { get; set; } = false;

        /// <summary>
        /// 是否對簽名資料的引數值進行UrlEncode
        /// </summary>
        public bool IsDoUrlEncodeForSourceValue { get; set; } = false;

        /// <summary>
        /// 簽名主體是否包含引數名
        /// </summary>
        public bool IsSignTextContainKey { get; set; } = true;

        /// <summary>
        /// 簽名主體中引數和引數值的連線符(需要啟用IsSignTextContainKey)
        /// </summary>
        public string SignTextKeyValueSeparator { get; set; } = "=";

        /// <summary>
        /// 簽名主體中不同引數項的連線符
        /// </summary>
        public string SignTextItemSeparator { get; set; } = "&";

        /// <summary>
        /// 編碼
        /// </summary>
        public Encoding DefaultEncoding { get; set; } = Encoding.UTF8;
    }
}

HttpSigner類

簽名元件的具體實現。

using System;
using System.Collections.Generic;
using System.Linq;

namespace JiuLing.CommonLibs.Security.HttpSign
{
    /// <summary>
    /// 網路請求籤名工具
    /// </summary>
    public class HttpSigner
    {
        /// <summary>
        /// 簽名設定
        /// </summary>
        private readonly HttpSignSetting _setting = new HttpSignSetting();
        /// <summary>
        /// 最終的簽名串
        /// </summary>
        private string _signString;

        /// <summary>
        /// 設定簽名資料
        /// </summary>
        /// <param name="signSource">待簽名的鍵值對</param>
        /// <param name="setting">設定簽名規則</param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public HttpSigner SetSignData(Dictionary<string, string> signSource, Action<HttpSignSetting> setting = null)
        {
            setting?.Invoke(_setting);
            if (_setting == null)
            {
                throw new ArgumentNullException("無效的簽名設定", "setting");
            }

            if (signSource == null || signSource.Count == 0)
            {
                throw new ArgumentException("待簽名資料異常", nameof(signSource));
            }

            var signSourceList = new List<HttpSignItem>(signSource.Count);
            foreach (var item in signSource)
            {
                var itemValue = item.Value;
                if (_setting.IsDoUrlEncodeForSourceValue)
                {
                    itemValue = System.Web.HttpUtility.UrlEncode(itemValue, _setting.DefaultEncoding);
                }
                signSourceList.Add(new HttpSignItem(item.Key, itemValue));
            }

            if (_setting.IsOrderByWithKey)
            {
                signSourceList = signSourceList.OrderBy(x => x.Key).ToList();
            }

            if (_setting.IsSignTextContainKey)
            {
                _signString = string.Join(_setting.SignTextItemSeparator, signSourceList.Select(x => $"{x.Key}{_setting.SignTextKeyValueSeparator}{x.Value}"));
            }
            else
            {
                _signString = string.Join(_setting.SignTextItemSeparator, signSourceList.Select(x => x.Value));
            }

            return this;
        }

        /// <summary>
        /// 簽名主體設定字首
        /// </summary>
        /// <param name="input">字首值</param>
        /// <returns></returns>
        public HttpSigner SetSignTextPrefix(string input)
        {
            _signString = $"{input}{_signString}";
            return this;
        }

        /// <summary>
        /// 簽名主體設定字尾
        /// </summary>
        /// <param name="input">字尾值</param>
        /// <returns></returns>
        public HttpSigner SetSignTextSuffix(string input)
        {
            _signString = $"{_signString}{input}";
            return this;
        }

        /// <summary>
        /// 簽名主體設定字尾
        /// </summary>
        /// <returns></returns>
        public HttpSigner SetUrlEncode()
        {
            _signString = System.Web.HttpUtility.UrlEncode(_signString, _setting.DefaultEncoding);
            return this;
        }

        /// <summary>
        /// 簽名主體進行Base64
        /// </summary>
        /// <returns></returns>
        public HttpSigner SetSignTextBase64()
        {
            _signString = Base64Utils.GetStringValue(_signString);
            return this;
        }

        /// <summary>
        /// 簽名主體進行MD5
        /// </summary>
        /// <param name="isToLower">簽名結果是否轉小寫</param>
        /// <returns></returns>
        public HttpSigner SetSignTextMD5(bool isToLower = true)
        {
            if (isToLower)
            {
                _signString = MD5Utils.GetStringValueToLower(_signString);
            }
            else
            {
                _signString = MD5Utils.GetStringValueToUpper(_signString);
            }
            return this;
        }

        /// <summary>
        /// 簽名主體進行SHA1
        /// </summary>
        /// <param name="isToLower">簽名結果是否轉小寫</param>
        /// <returns></returns>
        public HttpSigner SetSignTextSHA1(bool isToLower = true)
        {
            if (isToLower)
            {
                _signString = SHA1Utils.GetStringValueToLower(_signString);
            }
            else
            {
                _signString = SHA1Utils.GetStringValueToUpper(_signString);
            }
            return this;
        }

        /// <summary>
        /// 獲取簽名結果
        /// </summary>
        /// <returns></returns>
        public string GetSignResult()
        {
            return _signString;
        }
    }
}

5、附上倉庫地址

以上程式碼包含在我的通用類庫中,可以直接Nuget搜尋JiuLing.CommonLibs安裝。
GitHub類庫地址
文章程式碼地址