| 1 | using System.Security.Cryptography; |
| 2 | using Microsoft.Data.Sqlite; |
| 3 | using Isopoh.Cryptography.Argon2; |
| 4 | |
| 5 | namespace SimPas2_Windows |
| 6 | { |
| 7 | internal class MasterPasswordForm : Form |
| 8 | { |
| 9 | private readonly string mDatabasePath; |
| 10 | public byte[] EncryptionKey { get; private set; } |
| 11 | public bool IsValid { get; private set; } |
| 12 | |
| 13 | public MasterPasswordForm(string databasePath) |
| 14 | { |
| 15 | mDatabasePath = databasePath; |
| 16 | InitializeComponent(); |
| 17 | this.Icon = new Icon("simpas.ico"); |
| 18 | } |
| 19 | |
| 20 | private void InitializeComponent() |
| 21 | { |
| 22 | this.Text = "マスターパスワード"; |
| 23 | this.FormBorderStyle = FormBorderStyle.FixedDialog; |
| 24 | this.MaximizeBox = false; |
| 25 | this.MinimizeBox = false; |
| 26 | this.StartPosition = FormStartPosition.CenterScreen; |
| 27 | this.Width = 300; |
| 28 | this.Height = 150; |
| 29 | |
| 30 | var layout = new TableLayoutPanel |
| 31 | { |
| 32 | Dock = DockStyle.Fill, |
| 33 | ColumnCount = 1, |
| 34 | RowCount = 2, |
| 35 | Padding = new Padding(10) |
| 36 | }; |
| 37 | layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); |
| 38 | layout.RowStyles.Add(new RowStyle(SizeType.AutoSize)); |
| 39 | layout.RowStyles.Add(new RowStyle(SizeType.AutoSize)); |
| 40 | |
| 41 | TextBox masPasswordTextbox = new TextBox { Dock = DockStyle.Fill, UseSystemPasswordChar = true }; |
| 42 | Button masOkButton = new Button { Text = "OK", Dock = DockStyle.Right, Width = 80 }; |
| 43 | Button masCancelButton = new Button { Text = "キャンセル", Dock = DockStyle.Right, Width = 80 }; |
| 44 | |
| 45 | masOkButton.Click += (s, e) => |
| 46 | { |
| 47 | if (string.IsNullOrWhiteSpace(masPasswordTextbox.Text)) |
| 48 | { |
| 49 | MessageBox.Show("マスターパスワードは必須です。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); |
| 50 | return; |
| 51 | } |
| 52 | |
| 53 | try |
| 54 | { |
| 55 | if (VerifyOrSetMasterPassword(masPasswordTextbox.Text)) |
| 56 | { |
| 57 | EncryptionKey = DeriveKey(masPasswordTextbox.Text); |
| 58 | IsValid = VerifyKey(EncryptionKey); |
| 59 | DialogResult = DialogResult.OK; |
| 60 | Close(); |
| 61 | } |
| 62 | else |
| 63 | { |
| 64 | MessageBox.Show("不正なマスターパスワード。もう一度試してみて下さい。", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); |
| 65 | } |
| 66 | } |
| 67 | catch (Exception ex) |
| 68 | { |
| 69 | MessageBox.Show($"パスワードエラー:{ex.Message}", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); |
| 70 | } |
| 71 | }; |
| 72 | |
| 73 | masCancelButton.Click += (s, e) => { DialogResult = DialogResult.Cancel; Close(); }; |
| 74 | |
| 75 | layout.Controls.Add(masPasswordTextbox, 1, 0); |
| 76 | |
| 77 | FlowLayoutPanel buttonPanel = new FlowLayoutPanel |
| 78 | { |
| 79 | Dock = DockStyle.Fill, |
| 80 | FlowDirection = FlowDirection.RightToLeft |
| 81 | }; |
| 82 | buttonPanel.Controls.Add(masCancelButton); |
| 83 | buttonPanel.Controls.Add(masOkButton); |
| 84 | |
| 85 | layout.Controls.Add(buttonPanel, 0, 1); |
| 86 | layout.SetColumnSpan(buttonPanel, 2); |
| 87 | |
| 88 | this.Controls.Add(layout); |
| 89 | this.AcceptButton = masOkButton; |
| 90 | this.CancelButton = masCancelButton; |
| 91 | } |
| 92 | |
| 93 | private bool VerifyOrSetMasterPassword(string password) |
| 94 | { |
| 95 | using (SqliteConnection conn = new SqliteConnection($"Data Source={mDatabasePath}")) |
| 96 | { |
| 97 | conn.Open(); |
| 98 | |
| 99 | SqliteCommand createTable = conn.CreateCommand(); |
| 100 | createTable.CommandText = @" |
| 101 | CREATE TABLE IF NOT EXISTS Config ( |
| 102 | Id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 103 | Key VARCHAR(255) NOT NULL, |
| 104 | Value TEXT |
| 105 | )"; |
| 106 | createTable.ExecuteNonQuery(); |
| 107 | |
| 108 | SqliteCommand select = conn.CreateCommand(); |
| 109 | select.CommandText = "SELECT Value FROM Config WHERE Key = 'MasterPasswordHash'"; |
| 110 | using (SqliteDataReader reader = select.ExecuteReader()) |
| 111 | { |
| 112 | if (reader.Read()) |
| 113 | { |
| 114 | string storedHash = reader.GetString(0); |
| 115 | return Argon2.Verify(storedHash, password); |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | string passwordHash = Argon2.Hash(password); |
| 120 | SqliteCommand insert = conn.CreateCommand(); |
| 121 | insert.CommandText = "INSERT INTO Config (Key, Value) VALUES ('MasterPasswordHash', $value)"; |
| 122 | insert.Parameters.AddWithValue("$value", passwordHash); |
| 123 | insert.ExecuteNonQuery(); |
| 124 | |
| 125 | return true; |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | private byte[] DeriveKey(string password) |
| 130 | { |
| 131 | byte[] salt = GetOrCreateSalt(); |
| 132 | using (Rfc2898DeriveBytes derive = new Rfc2898DeriveBytes(password, salt, 100000, HashAlgorithmName.SHA256)) |
| 133 | { |
| 134 | return derive.GetBytes(32); |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | private byte[] GetOrCreateSalt() |
| 139 | { |
| 140 | using (SqliteConnection conn = new SqliteConnection($"Data Source={mDatabasePath}")) |
| 141 | { |
| 142 | conn.Open(); |
| 143 | |
| 144 | SqliteCommand createTable = conn.CreateCommand(); |
| 145 | createTable.CommandText = @" |
| 146 | CREATE TABLE IF NOT EXISTS Config ( |
| 147 | Id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 148 | Key VARCHAR(255) NOT NULL, |
| 149 | Value TEXT |
| 150 | )"; |
| 151 | createTable.ExecuteNonQuery(); |
| 152 | |
| 153 | SqliteCommand select = conn.CreateCommand(); |
| 154 | select.CommandText = "SELECT Value FROM Config WHERE Key = 'Salt'"; |
| 155 | using (SqliteDataReader reader = select.ExecuteReader()) |
| 156 | { |
| 157 | if (reader.Read()) |
| 158 | { |
| 159 | byte[] salt = new byte[16]; |
| 160 | reader.GetBytes(0, 0, salt, 0, 16); |
| 161 | return salt; |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | byte[] newSalt = RandomNumberGenerator.GetBytes(16); |
| 166 | SqliteCommand insert = conn.CreateCommand(); |
| 167 | insert.CommandText = "INSERT INTO Config (Key, Value) VALUES ('Salt', $value)"; |
| 168 | insert.Parameters.AddWithValue("$value", newSalt); |
| 169 | insert.ExecuteNonQuery(); |
| 170 | |
| 171 | return newSalt; |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | private bool VerifyKey(byte[] key) |
| 176 | { |
| 177 | using (SqliteConnection conn = new SqliteConnection($"Data Source={mDatabasePath}")) |
| 178 | { |
| 179 | conn.Open(); |
| 180 | SqliteCommand com = conn.CreateCommand(); |
| 181 | com.CommandText = "SELECT COUNT(*) FROM Passwords"; |
| 182 | long count = (long)com.ExecuteScalar(); |
| 183 | if (count == 0) return true; |
| 184 | |
| 185 | com.CommandText = "SELECT Password FROM Passwords LIMIT 1"; |
| 186 | using (SqliteDataReader reader = com.ExecuteReader()) |
| 187 | { |
| 188 | if (reader.Read()) |
| 189 | { |
| 190 | try |
| 191 | { |
| 192 | string encryptedPassword = reader.GetString(0); |
| 193 | byte[] combined = Convert.FromBase64String(encryptedPassword); |
| 194 | byte[] iv = new byte[16]; |
| 195 | byte[] encryptedBytes = new byte[combined.Length - iv.Length]; |
| 196 | |
| 197 | Buffer.BlockCopy(combined, 0, iv, 0, iv.Length); |
| 198 | Buffer.BlockCopy(combined, iv.Length, encryptedBytes, 0, encryptedBytes.Length); |
| 199 | |
| 200 | using (Aes aes = Aes.Create()) |
| 201 | { |
| 202 | aes.Key = key; |
| 203 | aes.IV = iv; |
| 204 | using (ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV)) |
| 205 | { |
| 206 | decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length); |
| 207 | return true; |
| 208 | } |
| 209 | } |
| 210 | } |
| 211 | catch |
| 212 | { |
| 213 | return false; |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | return true; |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | } |