System.out.print("Enter username: ");
String user = scanner.nextLine();
System.out.print("Enter password: ");
char[] password = console.readPassword();例如,我有这段代码,我想知道我这样做是否正确(将输入密码存储在char数组中)。现在真正的问题是,我应该如何将这个char[]密码与文本文件中的用户名和密码进行比较?而不将其转换为字符串。
发布于 2020-09-29 09:09:22
console.readPassword()之所以返回char[]而不是String,是因为字符串在Java语言中是不可变的,并且密码将驻留在应用程序的堆内存中,直到它最终被垃圾收集为止。同时,如果潜在的攻击者访问你的内存,他/她将以明文形式获得你的密码。
如果未将密码转换为字符串,则在使用完密码后,可以通过覆盖该char[]立即将其从内存中清除。有关这方面的更多信息,请参阅:Why is char[] preferred over String for passwords?
关于您的代码,如果您也能够以char[]的身份从文件中获得密码,则可以通过Arrays.equals(...)方法比较密码。参见下面的示例代码:
Console console = System.console();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter username: ");
String user = scanner.nextLine();
System.out.print("Enter password: ");
char[] password = console.readPassword();
String userInTextFile = "user"; // comes from the file
char[] passwordInTextFile = new char[] {'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}; // comes from the file
if (Objects.equals(user, userInTextFile) && Arrays.equals(passwordInTextFile, password)) {
System.out.println("Username and password are correct!");
} else {
System.out.println("Invalid credentials!");
}
Arrays.fill(password, '0'); // clean up the password from the memory
Arrays.fill(passwordInTextFile, '0'); // clean up the passwordInTextFile from the memory重要提示:实际上,你根本不应该比较明文密码。您应该使用现代密码散列函数(如Bcrypt、Scrypt、PBKDF2等)根据数据库中的hashed+salted密码验证用户提交的密码。
https://stackoverflow.com/questions/64111276
复制相似问题