last ...
This commit is contained in:
+29
-24
@@ -9,11 +9,29 @@ namespace xIds.Helpers
|
||||
/// </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()
|
||||
public static (string plainKey, string hash, string prefix) Generate(string keyPrefix)
|
||||
{
|
||||
//
|
||||
// Generate 32 bytes of cryptographically secure random data
|
||||
@@ -25,24 +43,19 @@ namespace xIds.Helpers
|
||||
|
||||
//
|
||||
// Format: xapp_{base64url}
|
||||
var plainKey = $"xapp_{Convert.ToBase64String(randomBytes)
|
||||
var plainKey = $"{keyPrefix}_{Convert.ToBase64String(randomBytes)
|
||||
.Replace("+", "-").Replace("/", "_").TrimEnd('=')}";
|
||||
|
||||
//
|
||||
// Hash with SHA256 for storage (never store plain key)
|
||||
using (var sha256 = SHA256.Create())
|
||||
{
|
||||
//
|
||||
var hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(plainKey));
|
||||
var hash = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
|
||||
// Compute Hash ...
|
||||
var hash = ComputeHash(plainKey);
|
||||
|
||||
//
|
||||
// Prefix for quick identification (first 12 chars)
|
||||
var prefix = plainKey.Substring(0, 16) + "...";
|
||||
//
|
||||
// Prefix for quick identification (first 12 chars)
|
||||
var prefix = plainKey.Substring(0, 16) + "...";
|
||||
|
||||
//
|
||||
return (plainKey, hash, prefix);
|
||||
}
|
||||
//
|
||||
return (plainKey, hash, prefix);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -57,16 +70,8 @@ namespace xIds.Helpers
|
||||
)
|
||||
{
|
||||
//
|
||||
using (var sha256 = SHA256.Create())
|
||||
{
|
||||
//
|
||||
var hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(plainKey));
|
||||
var computedHash = BitConverter.ToString(hashBytes)
|
||||
.Replace("-", "").ToLower();
|
||||
|
||||
//
|
||||
return computedHash == storedHash;
|
||||
}
|
||||
var hash = ComputeHash(plainKey);
|
||||
return hash == storedHash;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user