41 lines
1.3 KiB
C#
41 lines
1.3 KiB
C#
![]() |
using System;
|
|||
|
using System.Collections.Generic;
|
|||
|
using System.Linq;
|
|||
|
using System.Security.Cryptography;
|
|||
|
using System.Text;
|
|||
|
using System.Threading.Tasks;
|
|||
|
using VOL.Core.Configuration;
|
|||
|
|
|||
|
namespace VOL.Core.Utilities
|
|||
|
{
|
|||
|
/// <summary>
|
|||
|
/// IOT签名
|
|||
|
/// </summary>
|
|||
|
public static class IOTSignatureHelper
|
|||
|
{
|
|||
|
private static readonly string SecretKey = AppSetting.IOTConfig.SecretKey;
|
|||
|
private static readonly TimeSpan ValidDuration = TimeSpan.FromMinutes(AppSetting.IOTConfig.ExpirationDate); // 签名有效期
|
|||
|
|
|||
|
public static string GenerateSignature(string data, long timestamp)
|
|||
|
{
|
|||
|
string message = $"{data}:{timestamp}";
|
|||
|
using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(SecretKey)))
|
|||
|
{
|
|||
|
var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
|
|||
|
return Convert.ToBase64String(hash);
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
public static bool ValidateSignature(string data, long timestamp, string signature)
|
|||
|
{
|
|||
|
if (Math.Abs((DateTimeOffset.UtcNow.ToUnixTimeSeconds() - timestamp)) > ValidDuration.TotalSeconds)
|
|||
|
{
|
|||
|
return false; // 时间戳过期
|
|||
|
}
|
|||
|
|
|||
|
var generatedSignature = GenerateSignature(data, timestamp);
|
|||
|
return generatedSignature == signature;
|
|||
|
}
|
|||
|
}
|
|||
|
}
|