-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPasswordManager.java
More file actions
397 lines (337 loc) · 15.2 KB
/
Copy pathPasswordManager.java
File metadata and controls
397 lines (337 loc) · 15.2 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.*;
import java.util.Base64;
public class PasswordManager {
private static final String DATA_FILE = "passwords_data.dat";
private static final String FEISTEL_KEY = "MySecureKey123!@#";
private static final int FEISTEL_ROUNDS = 16;
private static Map<String, User> users = new HashMap<>();
private static List<StoredPassword> passwords = new ArrayList<>();
public static void main(String[] args) {
loadData();
runApplication();
saveData();
}
// ============ DATA PERSISTENCE ============
private static void saveData() {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(DATA_FILE))) {
oos.writeObject(users);
oos.writeObject(passwords);
System.out.println("✓ Данные сохранены");
} catch (IOException e) {
System.err.println("Ошибка сохранения данных: " + e.getMessage());
}
}
@SuppressWarnings("unchecked")
private static void loadData() {
File file = new File(DATA_FILE);
if (!file.exists()) {
System.out.println("✓ Новое хранилище паролей создано");
return;
}
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(DATA_FILE))) {
users = (Map<String, User>) ois.readObject();
passwords = (List<StoredPassword>) ois.readObject();
System.out.println("✓ Данные загружены");
} catch (IOException | ClassNotFoundException e) {
System.err.println("Ошибка загрузки данных: " + e.getMessage());
users = new HashMap<>();
passwords = new ArrayList<>();
}
}
// ============ APPLICATION MAIN LOOP ============
private static void runApplication() {
Scanner scanner = new Scanner(System.in);
User currentUser = null;
while (true) {
if (currentUser == null) {
System.out.println("\n========== МЕНЕДЖЕР ПАРОЛЕЙ ==========");
System.out.println("1. Регистрация");
System.out.println("2. Вход");
System.out.println("3. Выход");
System.out.print("Выберите действие: ");
String choice = scanner.nextLine().trim();
if (choice.equals("1")) {
currentUser = registerUser(scanner);
} else if (choice.equals("2")) {
currentUser = loginUser(scanner);
} else if (choice.equals("3")) {
System.out.println("До свидания!");
break;
} else {
System.out.println("Неверный выбор");
}
} else {
System.out.println("\n========== МЕНЮ ПОЛЬЗОВАТЕЛЯ ==========");
System.out.println("1. Сохранить новый пароль");
System.out.println("2. Просмотреть сохранённые пароли");
System.out.println("3. Удалить пароль");
System.out.println("4. Выход из аккаунта");
System.out.print("Выберите действие: ");
String choice = scanner.nextLine().trim();
if (choice.equals("1")) {
savePassword(scanner, currentUser);
} else if (choice.equals("2")) {
viewPasswords(currentUser);
} else if (choice.equals("3")) {
deletePassword(scanner, currentUser);
} else if (choice.equals("4")) {
currentUser = null;
System.out.println("Вы вышли из аккаунта");
} else {
System.out.println("Неверный выбор");
}
}
}
scanner.close();
}
// ============ USER AUTHENTICATION ============
private static User registerUser(Scanner scanner) {
System.out.print("Введите имя пользователя: ");
String username = scanner.nextLine().trim();
if (username.isEmpty() || username.length() < 3) {
System.out.println("✗ Имя пользователя должно быть минимум 3 символа");
return null;
}
if (users.containsKey(username)) {
System.out.println("✗ Пользователь с таким именем уже существует");
return null;
}
System.out.print("Введите пароль: ");
String password = scanner.nextLine();
if (password.isEmpty() || password.length() < 6) {
System.out.println("✗ Пароль должен быть минимум 6 символов");
return null;
}
String passwordHash = hashPassword(password);
User newUser = new User(username, passwordHash);
users.put(username, newUser);
System.out.println("✓ Пользователь успешно зарегистрирован");
return newUser;
}
private static User loginUser(Scanner scanner) {
System.out.print("Введите имя пользователя: ");
String username = scanner.nextLine().trim();
System.out.print("Введите пароль: ");
String password = scanner.nextLine();
User user = users.get(username);
if (user == null) {
System.out.println("✗ Пользователь не найден");
return null;
}
if (verifyPassword(password, user.passwordHash)) {
System.out.println("✓ Вход успешен");
return user;
} else {
System.out.println("✗ Неверный пароль");
return null;
}
}
// ============ PASSWORD MANAGEMENT ============
private static void savePassword(Scanner scanner, User user) {
System.out.print("Введите название сервиса: ");
String service = scanner.nextLine().trim();
System.out.print("Введите логин: ");
String login = scanner.nextLine();
System.out.print("Введите пароль: ");
String password = scanner.nextLine();
System.out.println("\nВыберите метод шифрования:");
System.out.println("1. Base64 (простое кодирование)");
System.out.println("2. MD5 (хеширование)");
System.out.println("3. Шифр Фейстеля (симметричное шифрование)");
System.out.println("4. MD5 с солью (хеширование + соль)");
System.out.print("Выберите метод (1-4): ");
String methodChoice = scanner.nextLine().trim();
String encryptedPassword = password;
String encryptionMethod = "";
String salt = null;
switch (methodChoice) {
case "1":
encryptedPassword = encryptBase64(password);
encryptionMethod = "base64";
break;
case "2":
encryptedPassword = encryptMD5(password);
encryptionMethod = "md5";
break;
case "3":
encryptedPassword = encryptFeistel(password);
encryptionMethod = "feistel";
break;
case "4":
salt = generateSalt();
encryptedPassword = encryptMD5WithSalt(password, salt);
encryptionMethod = "md5_salt";
break;
default:
System.out.println("✗ Неверный выбор");
return;
}
StoredPassword storedPassword = new StoredPassword(
user.username, service, login, encryptedPassword, encryptionMethod, salt);
passwords.add(storedPassword);
System.out.println("✓ Пароль успешно сохранён");
}
private static void viewPasswords(User user) {
List<StoredPassword> userPasswords = new ArrayList<>();
for (StoredPassword sp : passwords) {
if (sp.username.equals(user.username)) {
userPasswords.add(sp);
}
}
System.out.println("\n========== СОХРАНЁННЫЕ ПАРОЛИ ==========");
if (userPasswords.isEmpty()) {
System.out.println("Нет сохранённых паролей");
return;
}
for (int i = 0; i < userPasswords.size(); i++) {
StoredPassword sp = userPasswords.get(i);
System.out.println("\nID: " + i);
System.out.println("Сервис: " + sp.service);
System.out.println("Логин: " + sp.login);
System.out.println("Пароль (зашифрован): " + sp.password);
System.out.println("Метод: " + sp.encryptionMethod);
}
}
private static void deletePassword(Scanner scanner, User user) {
List<StoredPassword> userPasswords = new ArrayList<>();
List<Integer> indices = new ArrayList<>();
for (int i = 0; i < passwords.size(); i++) {
if (passwords.get(i).username.equals(user.username)) {
userPasswords.add(passwords.get(i));
indices.add(i);
}
}
System.out.print("Введите ID пароля для удаления: ");
String idStr = scanner.nextLine().trim();
try {
int id = Integer.parseInt(idStr);
if (id >= 0 && id < userPasswords.size()) {
passwords.remove((int) indices.get(id).intValue());
System.out.println("✓ Пароль удалён");
} else {
System.out.println("✗ Пароль не найден");
}
} catch (NumberFormatException e) {
System.err.println("✗ Ошибка: неверный ID");
}
}
// ============ ENCRYPTION METHODS ============
private static String encryptBase64(String password) {
return Base64.getEncoder().encodeToString(password.getBytes(StandardCharsets.UTF_8));
}
private static String encryptMD5(String password) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(password.getBytes());
return bytesToHex(messageDigest);
} catch (Exception e) {
throw new RuntimeException("MD5 encryption error", e);
}
}
private static String encryptMD5WithSalt(String password, String salt) {
try {
String saltedPassword = password + salt;
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(saltedPassword.getBytes());
return bytesToHex(messageDigest);
} catch (Exception e) {
throw new RuntimeException("MD5 with salt encryption error", e);
}
}
private static String generateSalt() {
byte[] salt = new byte[16];
new SecureRandom().nextBytes(salt);
return bytesToHex(salt);
}
private static String encryptFeistel(String password) {
byte[] plaintext = password.getBytes(StandardCharsets.UTF_8);
byte[] encrypted = feistelEncrypt(plaintext, FEISTEL_KEY.getBytes());
return bytesToHex(encrypted);
}
private static byte[] feistelEncrypt(byte[] plaintext, byte[] key) {
byte[] block = new byte[16];
System.arraycopy(plaintext, 0, block, 0, Math.min(plaintext.length, 16));
for (int round = 0; round < FEISTEL_ROUNDS; round++) {
byte[] left = new byte[8];
byte[] right = new byte[8];
System.arraycopy(block, 0, left, 0, 8);
System.arraycopy(block, 8, right, 0, 8);
byte[] fResult = feistelFunction(right, key, round);
byte[] newLeft = right;
byte[] newRight = xorBytes(left, fResult);
System.arraycopy(newLeft, 0, block, 0, 8);
System.arraycopy(newRight, 0, block, 8, 8);
}
return block;
}
private static byte[] feistelFunction(byte[] input, byte[] key, int round) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(input);
md.update(key);
md.update((byte) round);
return md.digest();
} catch (Exception e) {
throw new RuntimeException("Feistel function error", e);
}
}
private static byte[] xorBytes(byte[] a, byte[] b) {
byte[] result = new byte[Math.max(a.length, b.length)];
for (int i = 0; i < result.length; i++) {
byte aVal = i < a.length ? a[i] : 0;
byte bVal = i < b.length ? b[i] : 0;
result[i] = (byte) (aVal ^ bVal);
}
return result;
}
// ============ USER AUTHENTICATION HELPERS ============
private static String hashPassword(String password) {
return encryptMD5(password);
}
private static boolean verifyPassword(String password, String hash) {
return hashPassword(password).equals(hash);
}
private static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
// ============ DATA CLASSES ============
static class User implements Serializable {
static final long serialVersionUID = 1L;
String username;
String passwordHash;
User(String username, String passwordHash) {
this.username = username;
this.passwordHash = passwordHash;
}
}
static class StoredPassword implements Serializable {
static final long serialVersionUID = 1L;
String username;
String service;
String login;
String password;
String encryptionMethod;
String salt;
StoredPassword(String username, String service, String login, String password,
String encryptionMethod, String salt) {
this.username = username;
this.service = service;
this.login = login;
this.password = password;
this.encryptionMethod = encryptionMethod;
this.salt = salt;
}
}
}