using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
namespace MachineGuard;
///
/// Helper pubblico per la scrittura e la verifica del file secret di MachineGuard.
/// Usato da MachineGuardSetup e da eventuali script di deployment.
///
public static class MachineGuardSetupHelper
{
///
/// Cifra il token interno con DPAPI (LocalMachine scope) e lo scrive nel percorso specificato.
/// Crea la directory di destinazione se non esiste.
///
///
/// Percorso completo del file in cui salvare il secret cifrato.
/// Usare per il percorso di default.
///
[SupportedOSPlatform("windows")]
public static void WriteSecret(string secretFilePath)
{
ArgumentException.ThrowIfNullOrWhiteSpace(secretFilePath);
var tokenBytes = Encoding.UTF8.GetBytes(MachineGuardToken.ExpectedToken);
var encryptedBytes = ProtectedData.Protect(tokenBytes, null, DataProtectionScope.LocalMachine);
var directory = Path.GetDirectoryName(secretFilePath);
if (!string.IsNullOrEmpty(directory))
Directory.CreateDirectory(directory);
File.WriteAllBytes(secretFilePath, encryptedBytes);
}
///
/// Verifica che il file secret nel percorso specificato decifrabile con successo prima del deployment.
///
[SupportedOSPlatform("windows")]
public static bool VerifySecret(string secretFilePath)
{
if (!File.Exists(secretFilePath))
return false;
try
{
var encryptedBytes = File.ReadAllBytes(secretFilePath);
var decryptedBytes = ProtectedData.Unprotect(encryptedBytes, null, DataProtectionScope.LocalMachine);
var decryptedToken = Encoding.UTF8.GetString(decryptedBytes);
return string.Equals(decryptedToken, MachineGuardToken.ExpectedToken, StringComparison.Ordinal);
}
catch
{
return false;
}
}
///
/// Restituisce il percorso predefinito del file secret in base al sistema operativo corrente.
///
public static string GetDefaultSecretFilePath()
{
if (OperatingSystem.IsWindows())
{
var appData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
if (string.IsNullOrEmpty(appData))
appData = @"C:\ProgramData";
return Path.Combine(appData, "DataCoupler", "machine.guard");
}
return "/etc/datacoupler/machine.guard";
}
}