suwako / SimPass2-Windows アーカイブ

このリポジトリはアーカイブされています。読むだけで、プッシュやイシューの変更は出来ません。

8 KB、214行 生 Blame 履歴
1using Microsoft.Data.Sqlite;
2using System.Security.Cryptography;
3using System.Text;
4
5namespace SimPas2_Windows.Managers
6{
7 public class PasswordManager
8 {
9 private readonly string mConnectionString;
10 private readonly byte[] mEncryptionKey;
11 private readonly string mCulture;
12
13 private string mJpLang;
14
15 public PasswordManager(string databasePath, byte[] encryptionKey, string culture)
16 {
17 mConnectionString = $"Data Source={databasePath}";
18 mEncryptionKey = encryptionKey ?? throw new ArgumentNullException(nameof(encryptionKey));
19 mCulture = culture;
20
21 mJpLang = "ja-JP";
22 }
23
24 private bool AlreadyExists(string website, string username, int? excludeId = null)
25 {
26 using (SqliteConnection conn = new SqliteConnection(mConnectionString))
27 {
28 conn.Open();
29 SqliteCommand com = conn.CreateCommand();
30 com.CommandText = @"
31 SELECT COUNT(*) FROM Passwords
32 WHERE UPPER(Website) = UPPER(@website) AND UPPER(Username) = UPPER(@username)";
33 com.Parameters.AddWithValue("@website", website);
34 com.Parameters.AddWithValue("@username", username);
35
36 if (excludeId.HasValue)
37 {
38 com.CommandText += " AND Id != @excludeId";
39 com.Parameters.AddWithValue("@excludeId", excludeId.Value);
40 }
41
42 return Convert.ToInt32(com.ExecuteScalar()) > 0;
43 }
44 }
45
46 public void AddPassword(string website, string username, string password, string note)
47 {
48 if (string.IsNullOrWhiteSpace(website) || string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
49 {
50 string err = mCulture == mJpLang
51 ? "ウェブサイト、ユーザー名及び、パスワードを御入力下さい。"
52 : "Please fill in the website, user/email, and password.";
53 throw new ArgumentException(err);
54 }
55
56 if (AlreadyExists(website, username))
57 {
58 string err = mCulture == mJpLang
59 ? $"ウェブサイトとユーザー名「{website}/{username}」付きパスワードは既に存在します。"
60 : $"A password with the website and user/email of '{website}/{username}' already exists.";
61 throw new ArgumentException(err);
62 }
63
64 string encryptedPassword = EncryptPassword(password);
65 using (SqliteConnection conn = new SqliteConnection(mConnectionString))
66 {
67 conn.Open();
68 SqliteCommand com = conn.CreateCommand();
69 com.CommandText = @"
70 INSERT INTO Passwords (Website, Username, Password, Note)
71 VALUES ($website, $username, $password, $note)";
72 com.Parameters.AddWithValue("$website", website);
73 com.Parameters.AddWithValue("$username", username);
74 com.Parameters.AddWithValue("$password", encryptedPassword);
75 com.Parameters.AddWithValue("$note", string.IsNullOrEmpty(note) ? DBNull.Value : note);
76 com.ExecuteNonQuery();
77 }
78 }
79
80 public bool EditPassword(int id, string website, string username, string password, string note)
81 {
82 if (string.IsNullOrWhiteSpace(website) || string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
83 {
84 string err = mCulture == "ja-JP"
85 ? "ウェブサイト、ユーザー名及び、パスワードを御入力下さい。"
86 : "Please fill in the website, user/email, and password.";
87 throw new ArgumentException(err);
88 }
89
90 if (AlreadyExists(website, username, id))
91 {
92 string err = mCulture == mJpLang
93 ? $"ウェブサイトとユーザー名「{website}/{username}」付きパスワードは既に存在します。"
94 : $"A password with the website and user/email of '{website}/{username}' already exists.";
95 throw new ArgumentException(err);
96 }
97
98 string encryptedPassword = EncryptPassword(password);
99 using (SqliteConnection conn = new SqliteConnection(mConnectionString))
100 {
101 conn.Open();
102 SqliteCommand com = conn.CreateCommand();
103 com.CommandText = @"
104 UPDATE Passwords
105 SET Website = $website, Username = $username, Password = $password, Note = $note
106 WHERE Id = $id";
107 com.Parameters.AddWithValue("id", id);
108 com.Parameters.AddWithValue("$website", website);
109 com.Parameters.AddWithValue("$username", username);
110 com.Parameters.AddWithValue("$password", encryptedPassword);
111 com.Parameters.AddWithValue("$note", string.IsNullOrEmpty(note) ? DBNull.Value : note);
112
113 return com.ExecuteNonQuery() > 0;
114 }
115 }
116
117 public bool DeletePassword(int id)
118 {
119 using (SqliteConnection conn = new SqliteConnection(mConnectionString))
120 {
121 conn.Open();
122 SqliteCommand com = conn.CreateCommand();
123 com.CommandText = "DELETE FROM Passwords WHERE Id = $id";
124 com.Parameters.AddWithValue("$id", id);
125
126 return com.ExecuteNonQuery() > 0;
127 }
128 }
129
130 public List<(int Id, string Website, string Username, string Password, string Note)> GetAll(string keyword = "")
131 {
132 var passwords = new List<(int, string, string, string, string)>();
133 using (SqliteConnection conn = new SqliteConnection(mConnectionString))
134 {
135 conn.Open();
136 SqliteCommand com = conn.CreateCommand();
137 if (string.IsNullOrWhiteSpace(keyword))
138 {
139 com.CommandText = @"
140 SELECT Id, Website, Username, Password, Note FROM Passwords
141 ORDER BY Website ASC";
142 }
143 else
144 {
145 com.CommandText = @"
146 SELECT Id, Website, Username, Password, Note FROM Passwords
147 WHERE Website LIKE @keyword OR Username LIKE @keyword
148 ORDER BY Website ASC";
149 com.Parameters.AddWithValue("@keyword", $"%{keyword}%");
150 }
151
152 using (SqliteDataReader reader = com.ExecuteReader())
153 {
154 while (reader.Read())
155 {
156 string encryptedPassword = reader.GetString(3);
157 string decryptedPassword = DecryptPassword(encryptedPassword);
158 passwords.Add((
159 reader.GetInt32(0),
160 reader.GetString(1),
161 reader.GetString(2),
162 decryptedPassword,
163 reader.IsDBNull(4) ? string.Empty : reader.GetString(4)
164 ));
165 }
166 }
167 }
168
169 return passwords;
170 }
171
172 private string EncryptPassword(string plainPassword)
173 {
174 using (Aes aes = Aes.Create())
175 {
176 aes.Key = mEncryptionKey;
177 aes.GenerateIV();
178 byte[] iv = aes.IV;
179
180 using (var encryptor = aes.CreateEncryptor(aes.Key, iv))
181 {
182 byte[] plainBytes = Encoding.UTF8.GetBytes(plainPassword);
183 byte[] encryptedBytes = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
184 // Combine IV and encrypted data for storage
185 byte[] result = new byte[iv.Length + encryptedBytes.Length];
186 Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
187 Buffer.BlockCopy(encryptedBytes, 0, result, iv.Length, encryptedBytes.Length);
188 return Convert.ToBase64String(result);
189 }
190 }
191 }
192
193 private string DecryptPassword(string encryptedPassword)
194 {
195 byte[] combined = Convert.FromBase64String(encryptedPassword);
196 byte[] iv = new byte[16]; // AES IV is 16 bytes
197 byte[] encryptedBytes = new byte[combined.Length - iv.Length];
198 Buffer.BlockCopy(combined, 0, iv, 0, iv.Length);
199 Buffer.BlockCopy(combined, iv.Length, encryptedBytes, 0, encryptedBytes.Length);
200
201 using (Aes aes = Aes.Create())
202 {
203 aes.Key = mEncryptionKey;
204 aes.IV = iv;
205
206 using (var decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
207 {
208 byte[] decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
209 return Encoding.UTF8.GetString(decryptedBytes);
210 }
211 }
212 }
213 }
214}