using System.Security.Cryptography; using System.Text; using LumaTunnel.Client.Interface; using XFEExtension.NetCore.WinUIHelper.Implements.Services; namespace LumaTunnel.Client.Implements; public sealed class SecretStore : GlobalServiceBase, ISecretStore { private readonly string _directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "LumaTunnel", "secrets"); public async Task SetAsync(string key, string value, CancellationToken cancellationToken = default) { Directory.CreateDirectory(_directory); var plaintext = Encoding.UTF8.GetBytes(value); var encrypted = ProtectedData.Protect(plaintext, Entropy(key), DataProtectionScope.CurrentUser); await File.WriteAllBytesAsync(PathFor(key), encrypted, cancellationToken).ConfigureAwait(false); CryptographicOperations.ZeroMemory(plaintext); } public async Task GetAsync(string key, CancellationToken cancellationToken = default) { var path = PathFor(key); if (!File.Exists(path)) return null; var encrypted = await File.ReadAllBytesAsync(path, cancellationToken).ConfigureAwait(false); var plaintext = ProtectedData.Unprotect(encrypted, Entropy(key), DataProtectionScope.CurrentUser); try { return Encoding.UTF8.GetString(plaintext); } finally { CryptographicOperations.ZeroMemory(plaintext); } } public Task RemoveAsync(string key, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); var path = PathFor(key); if (File.Exists(path)) File.Delete(path); return Task.CompletedTask; } private string PathFor(string key) => Path.Combine(_directory, Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(key))) + ".secret"); private static byte[] Entropy(string key) => SHA256.HashData(Encoding.UTF8.GetBytes("LumaTunnel:" + key)); }