簡體   English   中英

你如何從文件中的文本中比較 char[] 數組(輸入)?

[英]How do you compare char[] array (input) from the text in file?

System.out.print("Enter username: ");
String user = scanner.nextLine();
System.out.print("Enter password: ");
char[] password = console.readPassword();

例如,我有這個代碼,我想知道我是否以正確的方式執行此操作(將輸入密碼存儲在字符數組中)。 現在真正的問題是我應該如何將這個 char[] 密碼與文本文件中的用戶名和密碼進行比較? 無需將其轉換為字符串。

console.readPassword()返回char[]而不是String的原因是因為 String 在 Java 中是不可變的,並且密碼將駐留在應用程序的堆內存中,直到它最終被垃圾收集。 同時,如果潛在的攻擊者可以訪問您的內存,他/她會以明文形式獲取您的密碼。

當密碼未轉換為字符串時,在完成密碼后,您可以通過覆蓋該char[]立即將其從內存中清除。 有關這方面的更多信息,請參閱: 為什么 char[] 優先於 String 作為密碼?

關於您的代碼,如果您也可以從文件中以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 等)根據數據庫中的散列+加鹽密碼驗證用戶提交的密碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM