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); } } }