TokenCombiner.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Bowin.Common.Utility;
  6. using System.Text.RegularExpressions;
  7. using System.Globalization;
  8. namespace Bowin.Common.ServiceToken
  9. {
  10. [Serializable]
  11. public class TokenCombiner
  12. {
  13. public static TokenView CreateToken(string systemCode, string password)
  14. {
  15. var timeStamp = DateTime.Now.ToString("yyyyMMddHHmmss");
  16. TokenView result = new TokenView();
  17. var validateString = systemCode + password + timeStamp;
  18. result.Token = validateString.MD5();
  19. result.TimeStamp = timeStamp;
  20. return result;
  21. }
  22. private static TokenError CheckTimeStamp(string timeStamp)
  23. {
  24. DateTime dt;
  25. if (!DateTime.TryParse(timeStamp, out dt))
  26. {
  27. if (!DateTime.TryParseExact(timeStamp, "yyyyMMddHHmmss", CultureInfo.CurrentCulture, DateTimeStyles.None, out dt))
  28. return new TokenError(-97, "时间戳格式错误");
  29. }
  30. var ts = DateTime.Now - dt;
  31. if (ts.TotalMinutes >= 15 || ts.TotalMinutes < -1)
  32. {
  33. return new TokenError(-98, "令牌超时。");
  34. }
  35. return null;
  36. }
  37. public static TokenError CheckTokenBySystemCode(string token, string systemCode, string timeStamp, string sysPwd)
  38. {
  39. var tokenError = CheckTimeStamp(timeStamp);
  40. if (tokenError != null)
  41. {
  42. return tokenError;
  43. }
  44. if (systemCode == null) return new TokenError(-97, "系统代码验证失败");
  45. var validateString = systemCode + sysPwd + timeStamp;
  46. var md5String = validateString.MD5();
  47. if (md5String.ToUpper() != token.ToUpper())
  48. {
  49. return new TokenError(-97, "令牌无效");
  50. }
  51. else
  52. {
  53. return null;
  54. }
  55. }
  56. }
  57. }