diff --git a/src/ScriptRunner/ScriptRunner.GUI/ScriptRunner.GUI.csproj b/src/ScriptRunner/ScriptRunner.GUI/ScriptRunner.GUI.csproj index 258d77b..7196fb8 100644 --- a/src/ScriptRunner/ScriptRunner.GUI/ScriptRunner.GUI.csproj +++ b/src/ScriptRunner/ScriptRunner.GUI/ScriptRunner.GUI.csproj @@ -37,6 +37,7 @@ + diff --git a/src/ScriptRunner/ScriptRunner.GUI/ViewModels/EncryptionHelper.cs b/src/ScriptRunner/ScriptRunner.GUI/ViewModels/EncryptionHelper.cs new file mode 100644 index 0000000..942b146 --- /dev/null +++ b/src/ScriptRunner/ScriptRunner.GUI/ViewModels/EncryptionHelper.cs @@ -0,0 +1,25 @@ +using System; +using System.Reflection; +using System.Security.Cryptography; +using System.Text; + +namespace ScriptRunner.GUI.ViewModels; + +public static class EncryptionHelper +{ + private static byte[] EntropyKey = Encoding.ASCII.GetBytes("80CD0C6D-74D3-4E6D-9E4F-ECA485E69FC7"); + + public static string Encrypt(string value) + { + byte[] data = Encoding.ASCII.GetBytes(value); + string protectedData = Convert.ToBase64String(ProtectedData.Protect(data, EntropyKey, DataProtectionScope.CurrentUser)); + return protectedData; + } + + public static string Decrypt(string value) + { + byte[] protectedData = Convert.FromBase64String(value); + string data = Encoding.ASCII.GetString(ProtectedData.Unprotect(protectedData, EntropyKey, DataProtectionScope.CurrentUser)); + return data; + } +} \ No newline at end of file diff --git a/src/ScriptRunner/ScriptRunner.GUI/ViewModels/VaultViewModel.cs b/src/ScriptRunner/ScriptRunner.GUI/ViewModels/VaultViewModel.cs index 866344d..ea47ab9 100644 --- a/src/ScriptRunner/ScriptRunner.GUI/ViewModels/VaultViewModel.cs +++ b/src/ScriptRunner/ScriptRunner.GUI/ViewModels/VaultViewModel.cs @@ -3,8 +3,6 @@ using System.Collections.ObjectModel; using System.IO; using System.Linq; -using System.Runtime.Versioning; -using System.Security.Cryptography; using System.Text; using System.Text.Json; using ReactiveUI; @@ -19,20 +17,27 @@ public static IReadOnlyList ReadFromVault() var vaultPath = AppSettingsService.GetSettingsPathFor("Vault.dat"); if (File.Exists(vaultPath)) { - File.Decrypt(vaultPath); - var content = File.ReadAllText(vaultPath); - File.Encrypt(vaultPath); - var data = JsonSerializer.Deserialize>(content); - return data ?? new List(); + var contentEncrypted = File.ReadAllText(vaultPath); + try + { + var content = EncryptionHelper.Decrypt(contentEncrypted); + var data = JsonSerializer.Deserialize>(content); + return data ?? new List(); + } + catch (Exception e) + { + //TODO: Invalid key + Console.WriteLine(e); + throw; + } } return Array.Empty(); } - public static void UpdateVault(List date) + public static void UpdateVault(List data) { var vaultPath = AppSettingsService.GetSettingsPathFor("Vault.dat"); - File.WriteAllText(vaultPath, JsonSerializer.Serialize(date), Encoding.UTF8); - File.Encrypt(vaultPath); + File.WriteAllText(vaultPath, EncryptionHelper.Encrypt(JsonSerializer.Serialize(data)), Encoding.UTF8); } }