ironlicensing-dotnet/SecureStorageLicenseCache.cs

108 lines
3.0 KiB
C#

using System.Text.Json;
using IronLicensing.Client.Models;
namespace IronLicensing.Client;
public class SecureStorageLicenseCache : ILicenseCache
{
private const string LicenseCacheKey = "iron_license_cache";
private const string SignatureCacheKey = "iron_license_signature";
private const string PublicKeyCacheKey = "iron_signing_public_key";
private const string RawJsonCacheKey = "iron_license_raw_json";
public async Task<CachedLicenseData?> GetCachedLicenseAsync()
{
try
{
var cached = await SecureStorage.Default.GetAsync(LicenseCacheKey);
if (string.IsNullOrEmpty(cached))
return null;
var license = JsonSerializer.Deserialize<LicenseInfo>(cached);
if (license == null)
return null;
var signature = await SecureStorage.Default.GetAsync(SignatureCacheKey);
var publicKey = await SecureStorage.Default.GetAsync(PublicKeyCacheKey);
var rawJson = await SecureStorage.Default.GetAsync(RawJsonCacheKey);
return new CachedLicenseData
{
License = license,
Signature = signature,
SigningPublicKey = publicKey,
RawLicenseJson = rawJson
};
}
catch
{
return null;
}
}
public async Task SaveLicenseAsync(LicenseInfo license, string? signature, string? signingPublicKey)
{
try
{
var json = JsonSerializer.Serialize(license);
await SecureStorage.Default.SetAsync(LicenseCacheKey, json);
await SecureStorage.Default.SetAsync(RawJsonCacheKey, json);
if (!string.IsNullOrEmpty(signature))
{
await SecureStorage.Default.SetAsync(SignatureCacheKey, signature);
}
if (!string.IsNullOrEmpty(signingPublicKey))
{
await SecureStorage.Default.SetAsync(PublicKeyCacheKey, signingPublicKey);
}
}
catch
{
// Ignore storage errors
}
}
public async Task<string?> GetSigningPublicKeyAsync()
{
try
{
return await SecureStorage.Default.GetAsync(PublicKeyCacheKey);
}
catch
{
return null;
}
}
public async Task SaveSigningPublicKeyAsync(string publicKey)
{
try
{
await SecureStorage.Default.SetAsync(PublicKeyCacheKey, publicKey);
}
catch
{
// Ignore storage errors
}
}
public Task ClearAsync()
{
try
{
SecureStorage.Default.Remove(LicenseCacheKey);
SecureStorage.Default.Remove(SignatureCacheKey);
SecureStorage.Default.Remove(PublicKeyCacheKey);
SecureStorage.Default.Remove(RawJsonCacheKey);
}
catch
{
// Ignore storage errors
}
return Task.CompletedTask;
}
}