using System.Security.Cryptography; namespace LumaTunnel.Server.Core.Security; public static class TokenUtilities { public static string CreateDeviceToken() => Base64UrlEncode(RandomNumberGenerator.GetBytes(32)); public static string CreatePairingCode() => Base64UrlEncode(RandomNumberGenerator.GetBytes(16)); public static string Hash(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); return Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(value))); } public static bool FixedTimeHashEquals(string value, string expectedHash) { if (string.IsNullOrWhiteSpace(value) || expectedHash.Length != 64) return false; Span actual = stackalloc byte[32]; Span expected = stackalloc byte[32]; SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(value), actual); if (!TryDecodeHex(expectedHash, expected)) return false; return CryptographicOperations.FixedTimeEquals(actual, expected); } private static string Base64UrlEncode(byte[] bytes) => Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); private static bool TryDecodeHex(ReadOnlySpan value, Span destination) { if (value.Length != destination.Length * 2) return false; for (var i = 0; i < destination.Length; i++) { var high = HexValue(value[i * 2]); var low = HexValue(value[(i * 2) + 1]); if (high < 0 || low < 0) return false; destination[i] = (byte)((high << 4) | low); } return true; } private static int HexValue(char value) => value switch { >= '0' and <= '9' => value - '0', >= 'a' and <= 'f' => value - 'a' + 10, >= 'A' and <= 'F' => value - 'A' + 10, _ => -1 }; }