-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPasswordVault.java
More file actions
102 lines (89 loc) · 2.95 KB
/
Copy pathPasswordVault.java
File metadata and controls
102 lines (89 loc) · 2.95 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
// PasswordVault.java
import java.io.*;
import java.util.*;
public class PasswordVault {
private static final String FILE_NAME = "vault.txt";
private String masterKey;
public PasswordVault(String masterKey) {
this.masterKey = masterKey;
}
public void addEntry(String site, String password) throws Exception {
String encrypted = CryptoUtil.encrypt(password, masterKey);
try (FileWriter fw = new FileWriter(FILE_NAME, true)) {
fw.write(site + ":" + encrypted + "\n");
}
}
public void viewEntries() throws Exception {
File file = new File(FILE_NAME);
if (!file.exists()) {
System.out.println("Vault is empty.");
return;
}
try (BufferedReader br = new BufferedReader(new FileReader(FILE_NAME))) {
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(":");
if (parts.length == 2) {
String decrypted = CryptoUtil.decrypt(parts[1], masterKey);
System.out.println(parts[0] + " -> " + decrypted);
}
}
}
}
// Edit an existing entry
public void editEntry(String site, String newPassword) throws Exception {
List<String> lines = new ArrayList<>();
boolean found = false;
try (BufferedReader br = new BufferedReader(new FileReader(FILE_NAME))) {
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(":");
if (parts[0].equalsIgnoreCase(site)) {
String encrypted = CryptoUtil.encrypt(newPassword, masterKey);
lines.add(site + ":" + encrypted);
found = true;
} else {
lines.add(line);
}
}
}
try (BufferedWriter bw = new BufferedWriter(new FileWriter(FILE_NAME))) {
for (String l : lines) {
bw.write(l);
bw.newLine();
}
}
if (found) {
System.out.println("Password updated successfully.");
} else {
System.out.println("Site not found.");
}
}
// Delete an entry
public void deleteEntry(String site) throws Exception {
List<String> lines = new ArrayList<>();
boolean found = false;
try (BufferedReader br = new BufferedReader(new FileReader(FILE_NAME))) {
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(":");
if (!parts[0].equalsIgnoreCase(site)) {
lines.add(line);
} else {
found = true;
}
}
}
try (BufferedWriter bw = new BufferedWriter(new FileWriter(FILE_NAME))) {
for (String l : lines) {
bw.write(l);
bw.newLine();
}
}
if (found) {
System.out.println("Password deleted successfully.");
} else {
System.out.println("Site not found.");
}
}
}