77 lines
2.2 KiB
C#
77 lines
2.2 KiB
C#
using System;
|
|
using System.Text;
|
|
using System.Security.Cryptography;
|
|
|
|
namespace xIds.Helpers
|
|
{
|
|
/// <summary>
|
|
/// Api Key Generating Helper Class ...
|
|
/// </summary>
|
|
public static class XApiKeyHelper
|
|
{
|
|
/// <summary>
|
|
/// Compute Hash of Specified Content using SHA256 ...
|
|
/// </summary>
|
|
/// <param name="plain"></param>
|
|
/// <returns></returns>
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Generate an Api Key ...
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Verify Generating Api Key ...
|
|
/// </summary>
|
|
/// <param name="plainKey"></param>
|
|
/// <param name="storedHash"></param>
|
|
/// <returns></returns>
|
|
public static bool Verify(
|
|
string plainKey,
|
|
string storedHash
|
|
)
|
|
{
|
|
//
|
|
var hash = ComputeHash(plainKey);
|
|
return hash == storedHash;
|
|
}
|
|
}
|
|
} |