Browse Source

Fix GlobalUserSecrets.LoadFromFile crash if not exist

pull/324/head
Ionite 1 year ago
parent
commit
b58ee4b1a5
No known key found for this signature in database
  1. 43
      StabilityMatrix.Core/Models/GlobalUserSecrets.cs

43
StabilityMatrix.Core/Models/GlobalUserSecrets.cs

@ -25,21 +25,22 @@ public class GlobalUserSecrets
public Dictionary<string, string> PatreonCookies { get; set; } = new();
public string? CivitApiToken { get; set; }
private static string? GetComputerSid()
{
var deviceId = new DeviceIdBuilder()
.AddMachineName()
.AddOsVersion()
.OnWindows(windows => windows
.OnWindows(
windows =>
windows
.AddProcessorId()
.AddMotherboardSerialNumber()
.AddSystemDriveSerialNumber())
.OnLinux(linux => linux
.AddMotherboardSerialNumber()
.AddSystemDriveSerialNumber())
.OnMac(mac => mac
.AddSystemDriveSerialNumber()
.AddPlatformSerialNumber())
)
.OnLinux(linux => linux.AddMotherboardSerialNumber().AddSystemDriveSerialNumber())
.OnMac(mac => mac.AddSystemDriveSerialNumber().AddPlatformSerialNumber())
.ToString();
return deviceId;
@ -63,14 +64,24 @@ public class GlobalUserSecrets
return result;
}
private static KeyInfo DeriveKeyWithSalt(SecureString password, int saltLength, int iterations, int keyLength)
private static KeyInfo DeriveKeyWithSalt(
SecureString password,
int saltLength,
int iterations,
int keyLength
)
{
var salt = RandomNumberGenerator.GetBytes(saltLength);
var key = DeriveKey(password, salt, iterations, keyLength);
return new KeyInfo(key, salt, iterations);
}
private static byte[] DeriveKey(SecureString password, byte[] salt, int iterations, int keyLength)
private static byte[] DeriveKey(
SecureString password,
byte[] salt,
int iterations,
int keyLength
)
{
var ptr = Marshal.SecureStringToBSTR(password);
try
@ -102,8 +113,7 @@ public class GlobalUserSecrets
private static (byte[], byte[]) EncryptBytes(byte[] data)
{
var keyInfo =
DeriveKeyWithSalt(GetComputerKeyPhrase(), SaltSize, Iterations, KeySize);
var keyInfo = DeriveKeyWithSalt(GetComputerKeyPhrase(), SaltSize, Iterations, KeySize);
using var aes = Aes.Create();
aes.Key = keyInfo.Key;
@ -117,8 +127,7 @@ public class GlobalUserSecrets
private static byte[] DecryptBytes(IReadOnlyCollection<byte> encryptedData, byte[] salt)
{
var key =
DeriveKey(GetComputerKeyPhrase(), salt, Iterations, KeySize);
var key = DeriveKey(GetComputerKeyPhrase(), salt, Iterations, KeySize);
using var aes = Aes.Create();
aes.Key = key;
@ -136,11 +145,19 @@ public class GlobalUserSecrets
var (encrypted, salt) = EncryptBytes(json);
// Prepend salt to encrypted json
var fileBytes = salt.Concat(encrypted).ToArray();
File.WriteAllBytes(fileBytes);
}
public static GlobalUserSecrets? LoadFromFile()
{
File.Info.Refresh();
if (!File.Exists)
{
return new GlobalUserSecrets();
}
var fileBytes = File.ReadAllBytes();
// Get salt from start of file

Loading…
Cancel
Save