a
This commit is contained in:
87
08.昶东/EastChanger/SignUtil.cs
Normal file
87
08.昶东/EastChanger/SignUtil.cs
Normal file
@@ -0,0 +1,87 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace EastChanger
|
||||
{
|
||||
public static class SignUtil
|
||||
{
|
||||
/// <summary>
|
||||
/// sign生成
|
||||
/// </summary>
|
||||
/// <param name="paramsMap"></param>
|
||||
/// <param name="secret"></param>
|
||||
/// <returns></returns>
|
||||
public static string BuildSign(Dictionary<string, object> paramsMap, string secret)
|
||||
{
|
||||
//var keySet = paramsMap.Keys;
|
||||
List<string> paramNames = paramsMap.Keys.ToList();
|
||||
paramNames.Sort();
|
||||
StringBuilder paramNameValue = new StringBuilder();
|
||||
foreach (var paramName in paramNames)
|
||||
{
|
||||
paramNameValue.Append(paramName).Append(paramsMap[paramName]);
|
||||
}
|
||||
string source = secret + paramNameValue.ToString() + secret;
|
||||
return ToMD5(source);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// MD加密
|
||||
/// </summary>
|
||||
/// <param name="message"></param>
|
||||
/// <returns></returns>
|
||||
public static string ToMD5(string message)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 1 创建一个提供信息摘要算法的对象,初始化为md5算法对象
|
||||
MD5 md5 = new MD5CryptoServiceProvider();
|
||||
// 2 将消息变成byte数组
|
||||
byte[] input = Encoding.UTF8.GetBytes(message);
|
||||
// 3 计算后获得字节数组,这就是那128位了
|
||||
byte[] buff = md5.ComputeHash(input);
|
||||
// 4 把数组每一字节(一个字节占八位)换成16进制连成md5字符串
|
||||
return Byte2hex(buff);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private static string Byte2hex(byte[] bytes)
|
||||
{
|
||||
//创建一个StringBuilder对象来存储最终的结果
|
||||
StringBuilder sign = new StringBuilder();
|
||||
//使用for循环遍历字节数组中的每个字节
|
||||
for (int i = 0; i < bytes.Length; i++)
|
||||
{
|
||||
// 将字节强制转换为整数,并对其进行位运算,即保留后八位的值,并转换为十六进制形式的字符串
|
||||
string hex = bytes[i].ToString("x2");
|
||||
// 如果转换后的字符串长度为1,即只有1位,则在前面添加一个0,以保证每个字节都是两位十六进制数
|
||||
if (hex.Length == 1)
|
||||
{
|
||||
sign.Append("0");
|
||||
}
|
||||
// 将转换后的字符串追加到StringBuilder对象中,并转换为大写形式
|
||||
sign.Append(hex.ToUpper());
|
||||
}
|
||||
return sign.ToString();
|
||||
}
|
||||
|
||||
public static string UrlEncode(string str)
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
byte[] byStr = System.Text.Encoding.UTF8.GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str)
|
||||
for (int i = 0; i < byStr.Length; i++)
|
||||
{
|
||||
sb.Append(@"%" + Convert.ToString(byStr[i], 16));
|
||||
}
|
||||
|
||||
return (sb.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user