我在这里停留了一个项目,我们得到了一个包含多个句子的txt文件,其中包含用户名,哈希密码和用户角色。我设法使用split函数将句子拆分为单个数组,但现在我迷失了如何搜索每个单独的句子以获得匹配的用户名/密码。任何帮助都非常感谢。
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.security.MessageDigest;
import java.util.Scanner;
public class Execute {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Scanner scnr = new Scanner(System.in);
FileInputStream fileByteStream = null;
String username = "";
String password = "";
Authentication user = new Authentication();
// Ask for user input
System.out.println("Enter your username");
username = scnr.nextLine();
System.out.println("Enter your password");
password = scnr.nextLine();
// Convert the password string to an MD5 hash
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(password.getBytes());
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
// Set the username and password to what the user entered
user.setUsername(username);
user.setPassword(sb.toString());
// open the credentials file
try {
fileByteStream = new FileInputStream("src/credentials.txt");
} catch (FileNotFoundException ex) {
System.out.println("File not found");
}
Scanner inFS = new Scanner(fileByteStream);
// inFS.useDelimiter("");
int lineNumber = 1;
while (inFS.hasNextLine()) {
String fileLine = inFS.nextLine(); // declares string "fileLine" to
// the next line in the file
String[] fileLineArray = fileLine.split("; "); // turns fileLine into
// an array name
// fileLineArray
lineNumber++; // increase line number by 1 each progression
if (fileLineArray[0].matches(user.getUsername())) {
System.out.println("Success");
} else {
System.out.println("Failed");
}
}
}
}
我不知道它是否有帮助,但这是另一堂课。
public class Authentication {
private String username;
private String password;
public Authentication(){
setUsername("");
setPassword("");
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
这也是凭证文件
griffin.keyes 108de81c31bf9c622f76876b74e9285f zookeeper;
rosario.dawson 3e34baa4ee2ff767af8c120a496742b5 admin;
bernie.gorilla a584efafa8f9ea7fe5cf18442f32b07b veterinarian;
donald.monkey 17b1b7d8a706696ed220bc414f729ad3 zookeeper;
jerome.grizzlybear 3adea92111e6307f8f2aae4721e77900 veterinarian;
bruce.grizzlybear 0d107d09f5bbe40cade3de5c71e9e9b7 admin;
答案 0 :(得分:1)
if (fileLineArray[0].contains(user.getUsername())) {
System.out.println("Success");
} else {
System.out.println("Failed");
}
尝试使用contains becasue
fileLineArray [0]是griffin.keyes 108de81c31bf9c622f76876b74e9285f 动物园管理员
或尝试进行不同的拆分并在文件中逐行搜索
使用
的readLine()
并在文件中使用令牌以进行更好的拆分
griffin.keyes-108de81c31bf9c622f76876b74e9285f-zookeeper
String[] fileLineArray = fileLine.split("-");
fileLineArray[0] will be griffin.keyes