You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
1.7 KiB
48 lines
1.7 KiB
using System;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
|
|
namespace Binance.TradeRobot.Common.Extensions
|
|
{
|
|
public static class CryptographyExtension
|
|
{
|
|
public static string ToHmacSha256(this string str, string secret, bool toBase64 = true)
|
|
{
|
|
secret = secret ?? "";
|
|
byte[] keyByte = Encoding.UTF8.GetBytes(secret);
|
|
byte[] strBytes = Encoding.UTF8.GetBytes(str);
|
|
using (var hmacsha256 = new HMACSHA256(keyByte))
|
|
{
|
|
byte[] hashStr = hmacsha256.ComputeHash(strBytes);
|
|
if (toBase64)
|
|
return Convert.ToBase64String(hashStr);
|
|
else
|
|
{
|
|
StringBuilder builder = new StringBuilder();
|
|
for (int i = 0; i < hashStr.Length; i++)
|
|
{
|
|
builder.Append(hashStr[i].ToString("x2"));
|
|
}
|
|
return builder.ToString();
|
|
}
|
|
}
|
|
}
|
|
|
|
public static string ToMD5(this string str, bool isUpper = false)
|
|
{
|
|
var format = isUpper ? "X2" : "x2";
|
|
//32位大写
|
|
using (var md5 = MD5.Create())
|
|
{
|
|
var data = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
|
|
StringBuilder builder = new StringBuilder();
|
|
// 循环遍历哈希数据的每一个字节并格式化为十六进制字符串
|
|
for (int i = 0; i < data.Length; i++)
|
|
{
|
|
builder.Append(data[i].ToString(format));
|
|
}
|
|
return builder.ToString();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|