API key protection

This commit is contained in:
Paul Schneider 2026-07-05 21:18:37 +01:00
commit 38bb7e40ef
7 changed files with 143 additions and 19 deletions

View file

@ -0,0 +1,50 @@
using System;
using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNetCore.DataProtection;
namespace isnd.Helpers
{
public static class ApiKeyProtector
{
private const byte LegacyDelta = 145;
public static string UnprotectWithFallback(IDataProtector protector, string protectedValue)
{
if (string.IsNullOrWhiteSpace(protectedValue))
{
return protectedValue;
}
try
{
return protector.Unprotect(protectedValue);
}
catch (CryptographicException)
{
return UnprotectLegacy(protectedValue);
}
catch (FormatException)
{
return UnprotectLegacy(protectedValue);
}
}
public static string UnprotectLegacy(string protectedValue)
{
if (string.IsNullOrWhiteSpace(protectedValue))
{
return protectedValue;
}
var bytes = Convert.FromBase64String(protectedValue);
var unprotectedBytes = new byte[bytes.Length];
for (var index = 0; index < bytes.Length; index++)
{
unprotectedBytes[index] = (byte)(bytes[index] ^ LegacyDelta);
}
return Encoding.UTF8.GetString(unprotectedBytes);
}
}
}