API key protection
This commit is contained in:
parent
cd72b7b9aa
commit
38bb7e40ef
7 changed files with 143 additions and 19 deletions
50
src/isnd/Helpers/ApiKeyProtector.cs
Normal file
50
src/isnd/Helpers/ApiKeyProtector.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue