using System; using System.Text; using System.Security.Cryptography; namespace xIds.Helpers { /// /// Api Key Generating Helper Class ... /// public static class XApiKeyHelper { /// /// Compute Hash of Specified Content using SHA256 ... /// /// /// public static string ComputeHash(string plain) { // using var sha256 = SHA256.Create(); var hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(plain)); var result = BitConverter.ToString(hashBytes) .Replace("-", "") .ToLower(); // return result; } /// /// Generate an Api Key ... /// /// public static (string plainKey, string hash, string prefix) Generate(string keyPrefix) { // // Generate 32 bytes of cryptographically secure random data var randomBytes = new byte[32]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(randomBytes); } // // Format: xapp_{base64url} var plainKey = $"{keyPrefix}_{Convert.ToBase64String(randomBytes) .Replace("+", "-").Replace("/", "_").TrimEnd('=')}"; // // Compute Hash ... var hash = ComputeHash(plainKey); // // Prefix for quick identification (first 12 chars) var prefix = plainKey.Substring(0, 16) + "..."; // return (plainKey, hash, prefix); } /// /// Verify Generating Api Key ... /// /// /// /// public static bool Verify( string plainKey, string storedHash ) { // var hash = ComputeHash(plainKey); return hash == storedHash; } } }