-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPassword.java
More file actions
76 lines (64 loc) · 2.61 KB
/
Password.java
File metadata and controls
76 lines (64 loc) · 2.61 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
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.management.RuntimeErrorException;
public class Password {
private static final String FILE_NAME = "admin_password.txt";
// Hash the password using SHA-256
public static String hashPassword(String password) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hashedBytes = md.digest(password.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : hashedBytes) {
hexString.append(String.format("%02x", b));
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Error hashing password", e);
}
}
public static String hashUsername(String name) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hashedBytes = md.digest(name.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : hashedBytes) {
hexString.append(String.format("%02x", b));
}
return hexString.toString();
} catch (Exception e) {
throw new RuntimeException("Error hashing UserName", e);
}
}
public static void savePassword(String hashedPassword) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_NAME))) {
writer.write(hashedPassword);
} catch (IOException e) {
System.out.println("Error saving password: " + e.getMessage());
}
}
public static void saveUserName(String hashedUserName) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("UserName.txt"))) {
writer.write(hashedUserName);
} catch (IOException e) {
System.out.println("Error saving password: " + e.getMessage());
}
}
public static String getStoredPassword() {
try (BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME))) {
return reader.readLine();
} catch (IOException e) {
System.out.println("Error reading password file: " + e.getMessage());
return null;
}
}
public static String getStoredUserName() {
try (BufferedReader reader = new BufferedReader(new FileReader("UserName.txt"))) {
return reader.readLine();
} catch (IOException e) {
System.out.println("Error reading password file: " + e.getMessage());
return null;
}
}
}