-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuth.java
More file actions
81 lines (69 loc) · 3.06 KB
/
Auth.java
File metadata and controls
81 lines (69 loc) · 3.06 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
import java.io.*;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.util.*;
class Auth {
static String usersFile = "users.txt";
static void registerUser(String username,String displayName, String password) {
try {
if (!isUsernameUnique(username)) {
System.out.println("Username already exists. Please choose another username.");
return;
}
KeyPair keyPair = RSA.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
byte[] encryptedPassword = RSA.encrypt(password, publicKey);
BufferedWriter writer = new BufferedWriter(new FileWriter(usersFile, true));
writer.write(username + ":" + displayName + ":" + Base64.getEncoder().encodeToString(encryptedPassword) +
":" + Base64.getEncoder().encodeToString(publicKey.getEncoded()) +
":" + Base64.getEncoder().encodeToString(privateKey.getEncoded()) + "\n");
writer.close();
System.out.println("Registration successful!");
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
static boolean loginUser(String username, String password) {
try {
BufferedReader reader = new BufferedReader(new FileReader(usersFile));
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(":");
if (parts.length >= 2 && parts[0].equals(username)) {
byte[] encryptedPassword = Base64.getDecoder().decode(parts[2]);
byte[] privateKeyBytes = Base64.getDecoder().decode(parts[4]);
PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
String decryptedPassword = RSA.decrypt(encryptedPassword, privateKey);
if (password.equals(decryptedPassword)) {
return true;
} else {
System.out.println("Invalid password. Please try again.");
return false;
}
}
}
System.out.println("User not found. Please register.");
return false;
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
return false;
}
}
static boolean isUsernameUnique(String username) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(usersFile));
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(":");
if (parts[0].equals(username)) {
return false;
}
}
return true;
}
static boolean checkPasswordMatching(String password1, String password2) {
return password1.equals(password2);
}
}