-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUser.cs
100 lines (86 loc) · 3.44 KB
/
User.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
namespace WpfApp2
{
public class User
{
private const string FilePath = "passwords.txt";
public void SavePassword(string label, string password)
{
if (string.IsNullOrWhiteSpace(label) || string.IsNullOrWhiteSpace(password))
throw new ArgumentException("Email/User and password cannot be empty.");
var passwords = LoadPasswords();
var encryptedLabel = EncryptionHelper.Encrypt(label);
if (passwords.ContainsKey(encryptedLabel))
{
throw new InvalidOperationException("A password with this Email/User already exists.");
}
passwords[encryptedLabel] = EncryptionHelper.Encrypt(password);
SavePasswords(passwords);
}
public Dictionary<string, string> GetPasswords()
{
var passwords = LoadPasswords();
var decryptedPasswords = new Dictionary<string, string>();
foreach (var kvp in passwords)
{
try
{
var decryptedLabel = EncryptionHelper.Decrypt(kvp.Key);
decryptedPasswords[decryptedLabel] = EncryptionHelper.Decrypt(kvp.Value);
}
catch (Exception ex)
{
throw new InvalidOperationException($"Failed to decrypt password for Email/User: {kvp.Key}", ex);
}
}
return decryptedPasswords;
}
public void RemovePassword(string label)
{
var passwords = LoadPasswords();
var encryptedLabel = EncryptionHelper.Encrypt(label);
if (!passwords.ContainsKey(encryptedLabel))
{
throw new ArgumentException("No password found with this Email/User.");
}
passwords.Remove(encryptedLabel);
SavePasswords(passwords);
}
private Dictionary<string, string> LoadPasswords()
{
if (!File.Exists(FilePath))
return new Dictionary<string, string>();
try
{
var encryptedData = File.ReadAllText(FilePath);
System.Diagnostics.Debug.WriteLine($"File content: {encryptedData}");
if (string.IsNullOrWhiteSpace(encryptedData))
return new Dictionary<string, string>();
return JsonConvert.DeserializeObject<Dictionary<string, string>>(encryptedData) ?? new Dictionary<string, string>();
}
catch (JsonException ex)
{
throw new IOException("Failed to parse the passwords file. The file might be corrupted.", ex);
}
catch (Exception ex)
{
throw new IOException("Failed to load passwords from file.", ex);
}
}
private void SavePasswords(Dictionary<string, string> passwords)
{
try
{
var encryptedData = JsonConvert.SerializeObject(passwords);
File.WriteAllText(FilePath, encryptedData);
}
catch (Exception ex)
{
throw new IOException("Failed to save passwords to file.", ex);
}
}
}
}