1
0

TypedHwid.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System.Collections.Immutable;
  2. using System.Diagnostics.CodeAnalysis;
  3. namespace Content.Shared.Database;
  4. /// <summary>
  5. /// Represents a raw HWID value together with its type.
  6. /// </summary>
  7. [Serializable]
  8. public sealed class ImmutableTypedHwid(ImmutableArray<byte> hwid, HwidType type)
  9. {
  10. public readonly ImmutableArray<byte> Hwid = hwid;
  11. public readonly HwidType Type = type;
  12. public override string ToString()
  13. {
  14. var b64 = Convert.ToBase64String(Hwid.AsSpan());
  15. return Type == HwidType.Modern ? $"V2-{b64}" : b64;
  16. }
  17. public static bool TryParse(string value, [NotNullWhen(true)] out ImmutableTypedHwid? hwid)
  18. {
  19. var type = HwidType.Legacy;
  20. if (value.StartsWith("V2-", StringComparison.Ordinal))
  21. {
  22. value = value["V2-".Length..];
  23. type = HwidType.Modern;
  24. }
  25. var array = new byte[GetBase64ByteLength(value)];
  26. if (!Convert.TryFromBase64String(value, array, out _))
  27. {
  28. hwid = null;
  29. return false;
  30. }
  31. // ReSharper disable once UseCollectionExpression
  32. // Do not use collection expression, C# compiler is weird and it fails sandbox.
  33. hwid = new ImmutableTypedHwid(ImmutableArray.Create(array), type);
  34. return true;
  35. }
  36. private static int GetBase64ByteLength(string value)
  37. {
  38. // Why is .NET like this man wtf.
  39. return 3 * (value.Length / 4) - value.TakeLast(2).Count(c => c == '=');
  40. }
  41. }
  42. /// <summary>
  43. /// Represents different types of HWIDs as exposed by the engine.
  44. /// </summary>
  45. public enum HwidType
  46. {
  47. /// <summary>
  48. /// The legacy HWID system. Should only be used for checking old existing database bans.
  49. /// </summary>
  50. Legacy = 0,
  51. /// <summary>
  52. /// The modern HWID system.
  53. /// </summary>
  54. Modern = 1,
  55. }