Last active
February 11, 2022 08:30
-
-
Save relyky/c93e644729583f1f3c5db654c9ff8606 to your computer and use it in GitHub Desktop.
short ticket, 產生短期門票
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace conShortSession | |
{ | |
class Program | |
{ | |
static object __lockObj = new object(); | |
static void Main(string[] args) | |
{ | |
for(int i=0;i<10;i++) | |
{ | |
ulong ticket = GenShortTicket(); | |
bool isValid = VerifyShortTicket(ticket); | |
Console.WriteLine($"ticket: {ticket}"); | |
Console.WriteLine($"isValue:{isValid}"); | |
} | |
Console.WriteLine("Press any key to continue."); | |
Console.ReadKey(); | |
} | |
static ulong GenShortTicket() | |
{ | |
lock (__lockObj) | |
{ | |
ulong tickSeed = ((ulong)DateTime.Now.Ticks) + 12345678987654321u; | |
System.Threading.SpinWait.SpinUntil(() => false, 97); //※Lock並等一小段時間以確保不重複 | |
byte[] by = BitConverter.GetBytes(tickSeed); | |
byte[] by2 = new byte[by.Length]; | |
int[] rnd = new int[] { 7, 1, 5, 3, 4, 2, 6, 0 }; | |
for (int i = 0; i < by.Length; i++) | |
{ | |
by2[i] = (byte)(by[rnd[i]] ^ 0xAA); | |
} | |
ulong ticket = BitConverter.ToUInt64(by2, 0); | |
return ticket; | |
} | |
} | |
static bool VerifyShortTicket(ulong ticket) | |
{ | |
byte[] by = BitConverter.GetBytes(ticket); | |
byte[] by2 = new byte[by.Length]; | |
int[] rnd = new int[] { 7, 1, 5, 3, 4, 2, 6, 0 }; | |
for (int i = 0; i < by.Length; i++) | |
{ | |
by2[i] = (byte)(by[rnd[i]] ^ 0xAA); | |
} | |
ulong tickSeed = BitConverter.ToUInt64(by2, 0); | |
DateTime pre = new DateTime((long)(tickSeed - 12345678987654321u)); | |
bool isValid = (DateTime.Now.Subtract(pre).TotalSeconds < 2); | |
return isValid; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment