36 lines
1.1 KiB
C#
36 lines
1.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
|
|
namespace Church.Net.Utility
|
|
{
|
|
public static class TokenHelper
|
|
{
|
|
public static string GenerateToken(string userId, DateTime? expiredTime=null)
|
|
{
|
|
|
|
if (expiredTime == null)
|
|
{
|
|
expiredTime = DateTime.Now.AddDays(2);
|
|
}
|
|
byte[] time = BitConverter.GetBytes(expiredTime.Value.ToBinary());
|
|
byte[] key = Encoding.ASCII.GetBytes(userId);
|
|
// byte[] expiredTimeByte = BitConverter.GetBytes(expiredTime.ToBinary());
|
|
string token = Convert.ToBase64String(time.Concat(key).ToArray());
|
|
return token;
|
|
}
|
|
public static string GetUserIdFromToken(string token)
|
|
{
|
|
byte[] data = Convert.FromBase64String(token);
|
|
DateTime when = DateTime.FromBinary(BitConverter.ToInt64(data, 0));
|
|
if (when >= DateTime.Now)
|
|
{
|
|
string userId = Encoding.ASCII.GetString(data.Skip(8).ToArray());
|
|
return userId;
|
|
}
|
|
return null;
|
|
}
|
|
}
|
|
}
|