front/SignatureHelper.cs
2026-01-24 11:55:01 +08:00

73 lines
2.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Security.Cryptography;
using System.Text;
/// <summary>
/// 签名算法:MD5(content + keys) 然后转base64
/// </summary>
public class SignatureHelper
{
/// <summary>
/// 生成签名
/// </summary>
/// <param name="content">待签名的内容</param>
/// <param name="charset">字符编码,通常为 "UTF-8"</param>
/// <param name="keys">密钥</param>
/// <returns>Base64编码的签名</returns>
public static string DoSign(string content, string charset, string keys)
{
try
{
// 拼接内容和密钥
string signContent = content + keys;
// 根据字符集获取编码
Encoding encoding = GetEncoding(charset);
// 计算MD5哈希
byte[] signBytes = encoding.GetBytes(signContent);
byte[] md5Hash = MD5.HashData(signBytes);
// 转换为Base64字符串
string sign = Convert.ToBase64String(md5Hash);
return sign;
}
catch (Exception ex)
{
throw new Exception($"签名失败: {ex.Message}", ex);
}
}
/// <summary>
/// 根据字符集名称获取编码对象
/// </summary>
private static Encoding GetEncoding(string charset)
{
if (string.IsNullOrEmpty(charset))
{
return Encoding.UTF8;
}
switch (charset.ToUpper())
{
case "UTF-8":
case "UTF8":
return Encoding.UTF8;
case "GBK":
return Encoding.GetEncoding("GBK");
case "GB2312":
return Encoding.GetEncoding("GB2312");
default:
try
{
return Encoding.GetEncoding(charset);
}
catch
{
return Encoding.UTF8;
}
}
}
}