java 如何使用 .equals() 方法比较两个密码(创建密码和确认密码)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16115922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 21:56:55  来源:igfitidea点击:

How do I compare two passwords (create password and confirm password) useing the .equals() method?

javaswingserializationpasswords

提问by hasherr

I'm building a simple create account user GUI that is integrated with my LogInScreen class. It creates a simple User, serializes it, and then lets me use that access in my log in program. The problem is, when I type in my passwords, they're never correct. I always get a problem where my program tells me that my passwords are not the same. I'm not sure how to fix this, and I would like to know how. I'll post my code below(the whole thing, along with my serializing class because the problem may be here).

我正在构建一个与我的 LogInScreen 类集成的简单创建帐户用户 GUI。它创建一个简单的用户,将其序列化,然后让我在登录程序中使用该访问权限。问题是,当我输入密码时,它们永远不会正确。我总是遇到一个问题,我的程序告诉我我的密码不一样。我不确定如何解决这个问题,我想知道如何解决。我将在下面发布我的代码(整个事情,以及我的序列化类,因为问题可能出在这里)。

User Class:

用户类别:

package passwordProgram;

import java.util.ArrayList;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.io.Serializable;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;

public class User implements Serializable, ActionListener {

    public static ArrayList<String> allUsernames = new ArrayList<String>();

    String username;
    String password;

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        User user = new User();
        user.mainGUI();
    }



    JFrame frame;
    JPanel panel;
    JTextField createUsername;
    JPasswordField createPassword;
    JPasswordField confirmPassword;
    JButton createAccount;
    JLabel noValid;

    public void mainGUI() {
        noValid = new JLabel();
        frame = new JFrame("Create a new account!");
        panel = new JPanel();
        panel.setBackground(Color.ORANGE);
        createPassword = new JPasswordField(10);
        confirmPassword = new JPasswordField(10);
        createUsername = new JTextField(10);
        JLabel userTxt = new JLabel("New Username: ");
        JLabel userPass = new JLabel("New Password: ");
        JLabel confirmPass = new JLabel("Confirm Password: ");
        createAccount = new JButton("Create your account!");

        panel.setLayout(new GridBagLayout());
        GridBagConstraints left = new GridBagConstraints();
        left.anchor = GridBagConstraints.WEST;
        GridBagConstraints right = new GridBagConstraints();
        right.anchor = GridBagConstraints.EAST;
        right.weightx = 2.0;
        right.fill = GridBagConstraints.HORIZONTAL;
        right.gridwidth = GridBagConstraints.REMAINDER;

        frame.getContentPane().add(BorderLayout.NORTH, noValid);
        frame.getContentPane().add(BorderLayout.CENTER, panel);
        panel.add(userTxt, left);
        panel.add(createUsername, right);
        panel.add(userPass, left);
        panel.add(createPassword, right);
        panel.add(confirmPass, left);
        panel.add(confirmPassword, right);

        frame.getContentPane().add(BorderLayout.SOUTH, createAccount);
        frame.setVisible(true);
        frame.setSize(500, 300);

        createAccount.addActionListener(this);
    }

    public void actionPerformed(ActionEvent event) {
        if (createUsername.getText().length() <= 0 ) {
            noValid.setText("That is not a valid username. Please try again.");
            frame.getContentPane().add(BorderLayout.NORTH, noValid);
        }

        else if (allUsernames.contains(createUsername.getText())) {
            noValid.setText("That username is already taken. Please try again.");
            frame.getContentPane().add(BorderLayout.NORTH, noValid);
        }

            //THIS IS THE PART I'M CONFUSED ABOUT
        else if (!(createPassword.getPassword().equals(confirmPassword.getPassword()))) {
            noValid.setText("Your passwords do not match!");
            frame.getContentPane().add(BorderLayout.NORTH, noValid);
        } else {    
            SaveUser sUser = new SaveUser();
            sUser.createAccount(this);
            noValid.setText("Account created successfully");
            frame.getContentPane().add(BorderLayout.NORTH, noValid);
        }
    }
}

And the serializing class:

和序列化类:

package passwordProgram;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class SaveUser {
    public void createAccount(User u) {
        try {
            FileOutputStream fileOS = new FileOutputStream("userInfo.txt");
            ObjectOutputStream objectOS = new ObjectOutputStream(fileOS);
            objectOS.writeObject(u);
            objectOS.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

回答by johnchen902

getPassword()returns char[], not String. Use

getPassword()返回char[],不是String。利用

!(Arrays.equals(createPassword.getPassword(), confirmPassword.getPassword()))

instead

反而

回答by Zim-Zam O'Pootertoot

Unless this is a toy project, you shouldn't store the passwords in plaintext. Instead, store a hash of the password; when the user logs in, hash the password and compare it to the stored hash. This question's accepted answer has some sample hashing code.

除非这是一个玩具项目,否则不应以明文形式存储密码。相反,存储密码的哈希值;当用户登录时,散列密码并将其与存储的散列进行比较。 这个问题的公认答案有一些示例散列代码

回答by Reimeus

You're comparing chararray Objects(returned by getPassword()) rather than than contents of the arrays themselves. The safest way to compare these 2 arrays is by using Arrays#equals:

您正在比较char数组Objects(由getPassword()返回)而不是数组本身的内容。比较这两个数组的最安全方法是使用Arrays#equals

else if (!(Arrays.equals(createPassword.getPassword(), 
                            confirmPassword.getPassword()))) {

回答by Jon Senchyna

JPasswordField.getPassword()returns a char[]. Calling array1.equals(array2)with two char arrays (like you are doing) will check if they are the same object reference, not if they have the same contents. You want to use `Array.equals(char[] array1, char[] array2), like so:

JPasswordField.getPassword()返回一个char[]. array1.equals(array2)使用两个字符数组调用(就像您正在做的那样)将检查它们是否是相同的对象引用,而不是它们是否具有相同的内容。您想使用`Array.equals(char[] array1, char[] array2),如下所示:

else if (!Array.equals(createPassword.getPassword(), confirmPassword.getPassword()))

回答by Michael Hall

getPassword()returns a char[]. So instead try:

getPassword()返回一个char[]. 因此,请尝试:

if (!(new String(createPassword.getPassword()).equals(new String(confirmPassword.getPassword()))