suwako / SimPass2-Windows アーカイブ

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

master
ブランチ master
SimPass2-Windows / Managers / OtpManager.cs
16.3 KB、479行 生 Blame 履歴
1using Microsoft.Data.Sqlite;
2using System.Security.Cryptography;
3using System.Text;
4
5namespace SimPas2_Windows.Managers
6{
7 public class OtpManager
8 {
9 private readonly string mConnectionString;
10 private readonly byte[] mEncryptionKey;
11 private readonly string mCulture;
12
13 private string mJpLang;
14
15 public OtpManager(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 secret, 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 Otp
32 WHERE UPPER(Website) = UPPER(@website) AND UPPER(Secret) = UPPER(@secret)";
33 com.Parameters.AddWithValue("@website", website);
34 com.Parameters.AddWithValue("@secret", secret);
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 AddOtp(string website, string secret, string issuer, string algorithm, int duration, int digits, string note)
47 {
48 if (string.IsNullOrWhiteSpace(website) || string.IsNullOrWhiteSpace(secret) || string.IsNullOrWhiteSpace(issuer))
49 {
50 string err = mCulture == mJpLang
51 ? "ウェブサイト、秘密鍵及び、発行者を御入力下さい。"
52 : "Please fill in the website, secret, and issuer.";
53 throw new ArgumentException(err);
54 }
55
56 string encryptedSecret = EncryptSecret(secret);
57
58 if (AlreadyExists(website, encryptedSecret))
59 {
60 string err = mCulture == mJpLang
61 ? $"ウェブサイト「{website}」向け秘密鍵は既に存在します。"
62 : $"An OTP with the website and secret for '{website}' already exists.";
63 throw new ArgumentException(err);
64 }
65
66 using (SqliteConnection conn = new SqliteConnection(mConnectionString))
67 {
68 conn.Open();
69 SqliteCommand com = conn.CreateCommand();
70 com.CommandText = @"
71 INSERT INTO Otp (Website, Secret, Issuer, Algorithm, Duration, Digits, Note)
72 VALUES ($website, $secret, $issuer, $algorithm, $duration, $digits, $note)";
73 com.Parameters.AddWithValue("$website", website);
74 com.Parameters.AddWithValue("$secret", encryptedSecret);
75 com.Parameters.AddWithValue("$issuer", issuer);
76 com.Parameters.AddWithValue("$algorithm", algorithm);
77 com.Parameters.AddWithValue("$duration", duration);
78 com.Parameters.AddWithValue("$digits", digits);
79 com.Parameters.AddWithValue("$note", string.IsNullOrEmpty(note) ? DBNull.Value : note);
80 com.ExecuteNonQuery();
81 }
82 }
83
84 public bool EditOtp(int id, string website, string secret, string issuer, string algorithm, int duration, int digits, string note)
85 {
86 if (string.IsNullOrWhiteSpace(website) || string.IsNullOrWhiteSpace(secret) || string.IsNullOrWhiteSpace(issuer))
87 {
88 string err = mCulture == mJpLang
89 ? "ウェブサイト、秘密鍵及び、発行者を御入力下さい。"
90 : "Please fill in the website, secret, and issuer.";
91 throw new ArgumentException(err);
92 }
93
94 string encryptedSecret = EncryptSecret(secret);
95
96 if (AlreadyExists(website, encryptedSecret, id))
97 {
98 string err = mCulture == mJpLang
99 ? $"ウェブサイト「{website}」向け秘密鍵は既に存在します。"
100 : $"An OTP with the website and secret for '{website}' already exists.";
101 throw new ArgumentException(err);
102 }
103
104 using (SqliteConnection conn = new SqliteConnection(mConnectionString))
105 {
106 conn.Open();
107 SqliteCommand com = conn.CreateCommand();
108 com.CommandText = @"
109 UPDATE Otp
110 SET Website = $website, Secret = $secret, Issuer = $issuer, Algorithm = $algorithm, Duration = $duration, Digits = $digits, Note = $note
111 WHERE Id = $id";
112 com.Parameters.AddWithValue("$id", id);
113 com.Parameters.AddWithValue("$website", website);
114 com.Parameters.AddWithValue("$secret", encryptedSecret);
115 com.Parameters.AddWithValue("$issuer", issuer);
116 com.Parameters.AddWithValue("$algorithm", algorithm);
117 com.Parameters.AddWithValue("$duration", duration);
118 com.Parameters.AddWithValue("$digits", digits);
119 com.Parameters.AddWithValue("$note", string.IsNullOrEmpty(note) ? DBNull.Value : note);
120 return com.ExecuteNonQuery() > 0;
121 }
122 }
123
124 public bool DeleteOtp(int id)
125 {
126 using (SqliteConnection conn = new SqliteConnection(mConnectionString))
127 {
128 conn.Open();
129 SqliteCommand com = conn.CreateCommand();
130 com.CommandText = "DELETE FROM Otp WHERE Id = $id";
131 com.Parameters.AddWithValue("$id", id);
132 return com.ExecuteNonQuery() > 0;
133 }
134 }
135
136 public List<(int Id, string Website, string Secret, string Issuer, string Algorithm, int Duration, int Digits, string Note)> GetAll(string keyword = "")
137 {
138 var otps = new List<(int, string, string, string, string, int, int, string)>();
139 using (SqliteConnection conn = new SqliteConnection(mConnectionString))
140 {
141 conn.Open();
142 SqliteCommand com = conn.CreateCommand();
143 if (string.IsNullOrWhiteSpace(keyword))
144 {
145 com.CommandText = @"
146 SELECT Id, Website, Secret, Issuer, Algorithm, Duration, Digits, Note FROM Otp
147 ORDER BY Website ASC";
148 }
149 else
150 {
151 com.CommandText = @"
152 SELECT Id, Website, Secret, Issuer, Algorithm, Duration, Digits, Note FROM Otp
153 WHERE Website LIKE @keyword OR Issuer LIKE @keyword
154 ORDER BY Website ASC";
155 com.Parameters.AddWithValue("@keyword", $"%{keyword}%");
156 }
157
158 using (SqliteDataReader reader = com.ExecuteReader())
159 {
160 while (reader.Read())
161 {
162 string encryptedSecret = reader.GetString(2);
163 string decryptedSecret = DecryptSecret(encryptedSecret);
164 otps.Add((
165 reader.GetInt32(0),
166 reader.GetString(1),
167 decryptedSecret,
168 reader.GetString(3),
169 reader.GetString(4),
170 reader.GetInt32(5),
171 reader.GetInt32(6),
172 reader.IsDBNull(7) ? string.Empty : reader.GetString(7)
173 ));
174 }
175 }
176 }
177
178 return otps;
179 }
180
181 public (string Code, string Error) GenerateTotp(string secret, int digits, string algorithm, int duration = 30)
182 {
183 try
184 {
185 var (sec, error) = ExtractSecret(secret);
186 if (!string.IsNullOrEmpty(error))
187 {
188 return ("", error);
189 }
190
191 long currentTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
192 ulong counter = (ulong)(currentTime / duration);
193 uint totp = GenerateTotpCode(sec, counter, digits, algorithm);
194 return (totp.ToString($"D{digits}"), "");
195 }
196 catch (Exception ex)
197 {
198 return ("", $"TOTP generation error: {ex.Message}");
199 }
200 }
201
202 private (byte[]? Secret, string Error) ExtractSecret(string otpauthUrl)
203 {
204 if (string.IsNullOrEmpty(otpauthUrl))
205 {
206 string err = mCulture == mJpLang
207 ? "OTP Authを御入力下さい。"
208 : "Please fill in the OTP Auth.";
209 throw new ArgumentException(err);
210 }
211
212 if (!otpauthUrl.StartsWith("otpauth://totp/", StringComparison.OrdinalIgnoreCase))
213 {
214 try
215 {
216 byte[] secretDecoded = Base32Decode(otpauthUrl);
217 return (secretDecoded, "");
218 }
219 catch (Exception ex)
220 {
221 string err = mCulture == mJpLang
222 ? $"TOTP秘密鍵を復号化に失敗:{ex.Message}"
223 : $"Failed to decode TOTP secret: {ex.Message}";
224 return (null, err);
225 }
226 }
227
228 int secretStart = otpauthUrl.IndexOf("secret=", StringComparison.OrdinalIgnoreCase);
229 if (secretStart == -1)
230 {
231 string err = mCulture == mJpLang
232 ? "TOTP秘密鍵をURLの中に見つけられませんでした。"
233 : "TOTP secret not found in URL";
234 return (null, err);
235 }
236
237 secretStart += 7;
238
239 int secretEnd = otpauthUrl.IndexOf('&', secretStart);
240 if (secretEnd == -1)
241 {
242 secretEnd = otpauthUrl.Length;
243 }
244
245 if (secretEnd <= secretStart)
246 {
247 string err = mCulture == mJpLang
248 ? "不正なTOTP秘密枠"
249 : "Invalid TOTP secret range";
250 return (null, err);
251 }
252
253 string secretEncoded = otpauthUrl.Substring(secretStart, secretEnd - secretStart);
254
255 try
256 {
257 byte[] secretDecoded = Base32Decode(secretEncoded);
258 return (secretDecoded, "");
259 }
260 catch (Exception ex)
261 {
262 string err = mCulture == mJpLang
263 ? $"TOTP秘密鍵を復号化に失敗:{ex.Message}"
264 : $"Failed to decode TOTP secret: {ex.Message}";
265 return (null, err);
266 }
267 }
268
269 public (string Secret, string Issuer, string Algorithm, int Duration, int Digits) ParseOtpAuthUrl(string otpAuthUrl)
270 {
271 if (string.IsNullOrEmpty(otpAuthUrl) || !otpAuthUrl.StartsWith("otpauth://totp/", StringComparison.OrdinalIgnoreCase))
272 {
273 string err = mCulture == mJpLang
274 ? "不正なOTP Auth URL"
275 : "Invalid OTP Auth URL";
276 throw new ArgumentException(err);
277 }
278
279 string issuer = "";
280 string algorithm = "SHA1";
281 int duration = 30;
282 int digits = 6;
283
284 int labelStart = "otpauth://totp/".Length;
285 int labelEnd = otpAuthUrl.IndexOf('?', labelStart);
286 if (labelEnd != -1)
287 {
288 issuer = otpAuthUrl.Substring(labelStart, labelEnd - labelStart);
289 if (issuer.Contains(':'))
290 {
291 issuer = issuer.Substring(0, issuer.IndexOf(':'));
292 }
293 }
294
295 int secretStart = otpAuthUrl.IndexOf("secret=", StringComparison.OrdinalIgnoreCase);
296 if (secretStart == -1)
297 {
298 string err = mCulture == mJpLang
299 ? "TOTP秘密鍵をURLの中に見つけられませんでした。"
300 : "TOTP secret not found in URL";
301 throw new ArgumentException(err);
302 }
303 secretStart += 7;
304 int secretEnd = otpAuthUrl.IndexOf('&', secretStart);
305 if (secretEnd == -1)
306 {
307 secretEnd = otpAuthUrl.Length;
308 }
309 string secret = otpAuthUrl.Substring(secretStart, secretEnd - secretStart);
310
311 var queryParams = otpAuthUrl.Substring(labelEnd + 1).Split('&').Select(p => p.Split('=')).ToDictionary(p => p[0].ToLower(), p => p.Length > 1 ? p[1] : "");
312 if (queryParams.ContainsKey("issuer"))
313 {
314 issuer = queryParams["issuer"];
315 }
316 if (queryParams.ContainsKey("algorithm"))
317 {
318 algorithm = queryParams["algorithm"].ToUpper();
319 if (algorithm != "SHA1" && algorithm != "SHA256" && algorithm != "SHA512")
320 {
321 algorithm = "SHA1";
322 }
323 }
324 if (queryParams.ContainsKey("period") && int.TryParse(queryParams["period"], out int parsedPeriod))
325 {
326 duration = parsedPeriod;
327 }
328 if (queryParams.ContainsKey("digits") && int.TryParse(queryParams["digits"], out int parsedDigits))
329 {
330 digits = parsedDigits;
331 }
332
333 return (secret, issuer, algorithm, duration, digits);
334 }
335
336 private uint GenerateTotpCode(byte[] secret, ulong counter, int digits, string algorithm)
337 {
338 byte[] counterBytes = BitConverter.GetBytes(counter);
339 if (BitConverter.IsLittleEndian)
340 {
341 Array.Reverse(counterBytes);
342 }
343
344 using (HMAC hmac = algorithm.ToUpper() switch
345 {
346 "SHA256" => new HMACSHA256(secret),
347 "SHA512" => new HMACSHA512(secret),
348 _ => new HMACSHA1(secret),
349 })
350 {
351 byte[] hash = hmac.ComputeHash(counterBytes);
352 int offset = hash[hash.Length - 1] & 0x0F;
353 uint truncatedHash =
354 (uint)(hash[offset] & 0x7F) << 24 |
355 (uint)(hash[offset + 1] & 0xFF) << 16 |
356 (uint)(hash[offset + 2] & 0xFF) << 8 |
357 (uint)(hash[offset + 3] & 0xFF);
358
359 return truncatedHash % (uint)Math.Pow(10, digits);
360 }
361 }
362
363 private byte[] Base32Decode(string base32)
364 {
365 const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
366
367 if (string.IsNullOrEmpty(base32))
368 {
369 string err = mCulture == mJpLang
370 ? "Base32文字はnullや空です。"
371 : "Base32 string cannot be null or empty";
372 throw new ArgumentException(err);
373 }
374
375 // Remove spaces, hyphens, and convert to uppercase
376 base32 = base32.Trim().Replace(" ", "").Replace("-", "").ToUpper();
377 // Count padding characters
378 int padding = 0;
379 for (int i = base32.Length - 1; i >= 0 && base32[i] == '='; i--)
380 {
381 padding++;
382 }
383
384 // Remove padding for processing
385 string cleanBase32 = base32.Substring(0, base32.Length - padding);
386 if (cleanBase32.Any(c => !alphabet.Contains(c)))
387 {
388 string err = mCulture == mJpLang
389 ? "Base32文字は不正文字が含みます。"
390 : "Base32 string contains invalid characters";
391 throw new ArgumentException(err);
392 }
393
394 // Calculate output length
395 int byteCount = cleanBase32.Length * 5 / 8;
396 if (byteCount == 0)
397 {
398 return Array.Empty<byte>();
399 }
400
401 byte[] buffer = new byte[byteCount];
402 int bufferIndex = 0;
403 int bits = 0;
404 int bitCount = 0;
405
406 foreach (char c in cleanBase32)
407 {
408 int value = alphabet.IndexOf(c);
409 if (value < 0)
410 {
411 string err = mCulture == mJpLang
412 ? "Base32文字は不正文字が含みます。"
413 : "Base32 string contains invalid characters";
414 throw new ArgumentException(err);
415 }
416
417 bits = bits << 5 | value;
418 bitCount += 5;
419
420 if (bitCount >= 8)
421 {
422 buffer[bufferIndex++] = (byte)(bits >> bitCount - 8);
423 bitCount -= 8;
424 }
425 }
426
427 // Resize to actual bytes written
428 if (bufferIndex < byteCount)
429 {
430 Array.Resize(ref buffer, bufferIndex);
431 }
432
433 return buffer;
434 }
435
436 private string EncryptSecret(string secret)
437 {
438 using (Aes aes = Aes.Create())
439 {
440 aes.Key = mEncryptionKey;
441 aes.GenerateIV();
442 byte[] iv = aes.IV;
443
444 using (ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, iv))
445 {
446 byte[] plainBytes = Encoding.UTF8.GetBytes(secret);
447 byte[] encryptedBytes = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
448 byte[] result = new byte[iv.Length + encryptedBytes.Length];
449
450 Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
451 Buffer.BlockCopy(encryptedBytes, 0, result, iv.Length, encryptedBytes.Length);
452
453 return Convert.ToBase64String(result);
454 }
455 }
456 }
457
458 private string DecryptSecret(string encryptedSecret)
459 {
460 byte[] combined = Convert.FromBase64String(encryptedSecret);
461 byte[] iv = new byte[16];
462 byte[] encryptedBytes = new byte[combined.Length - iv.Length];
463 Buffer.BlockCopy(combined, 0, iv, 0, iv.Length);
464 Buffer.BlockCopy(combined, iv.Length, encryptedBytes, 0, encryptedBytes.Length);
465
466 using (Aes aes = Aes.Create())
467 {
468 aes.Key = mEncryptionKey;
469 aes.IV = iv;
470
471 using (ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
472 {
473 byte[] decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
474 return Encoding.UTF8.GetString(decryptedBytes);
475 }
476 }
477 }
478 }
479}