password check using hashmap - java

I want to check username and password using this action listener method
but I always get Wrong password!
public void actionPerformed(ActionEvent arg0) {
String uN = usernameFiled.getText();
String pass = passwordField.getPassword().toString();
//
if (uN.isEmpty() || pass.isEmpty()){
JOptionPane.showMessageDialog(LoginPage.this, "Fields should not be empty!", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
HashMap<String, User> users = UserDAO.getInstance().getUsers();
User temp = users.get(uN);
if (temp.getPassword().equals(pass)){
JOptionPane.showMessageDialog(LoginPage.this, "Login successfull", "Success", JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(LoginPage.this, "Wrong username or password", "Error ", JOptionPane.ERROR_MESSAGE);
}
}
});
What is the problem of code??

JPasswordField#getPassword returns the text contained in this TextComponent in char[]. char[].toString() does not return the string value, array.toString actually returns the name of the variable and hascode.
you should call new String(passwordField.getPassword()) or String.valueOf(passwordField.getPassword())
try -
String pass = new String(passwordField.getPassword());
or
String pass = String.valueOf(passwordField.getPassword());

passwordField.getPassword() return char[]. So by calling toString() give you the object string of char[].So, The statement you are using, do not give you password.
String pass = passwordField.getPassword().toString();
Use it in following way.
String pass = new String(passwordField.getPassword());

Related

How to create a Java 2-Step authentication on Java 8?

Hello everyone at StackOverflow,
I will be asking a question that I'm confused about and searched for hours for, it's to put a 2-Step authentication on a Java program, what I want is that is send a generated code to a login page like the one I created below.
package log;
import javax.swing.JOptionPane;
public class Login {
public static void main(String args[]) {
String username = JOptionPane.showInputDialog("Enter your username");
String password = JOptionPane.showInputDialog("Enter your password");
if (
username != null && password != null &&
(
(username.equals("g17") && password.equals("ire35")) ||
(username.equals("ree") && password.equals("melikejava")) ||
(username.equals("citizenzap") && password.equals("javarules23"))||
(username.equals("devs") && password.equals("password"))
)
)
{
JOptionPane.showMessageDialog(null, "Logged in!" );
} else {
JOptionPane.showMessageDialog(null, "Incorrect username or password! Try again later." );
}
}
}
Everything is fine with the code above, it's just that I want to send a randomly generated code to a phone number, like as I said before a 2-Step verification. Like Google has or Microsoft and etc. For example: You write a phone number, 123-456-7890, then it sends a code to the phone number and it's says something like Your code is 178634 then you write it into the input box, then it checks if it was the code it sent.
If the question I said is not specific enough or something like that please tell me.
Thanks and keep on coding!
-CitizenZap
First, I suggest you put your data in map, combine username, password, phoneNumber into one class, like UserInfo. Because you need to bind phoneNumber to user, or any phoneNumber after login is acceptable.
Then, you replace
{
JOptionPane.showMessageDialog(null, "Logged in!" );
}
with
String newPhoneNumber = null;
{
newPhoneNumber = JOptionPane.showInputDialog("Enter your phone number");
}
You need to check if newPhoneNumber equals with the phoneNumber bind to the user.
// this should be in a while(true) loop
if (newPhoneNumber.equals(phoneNumber)) {
sendSms(phoneNumber);
String code = JOptionPane.showInputDialog("Enter your code");
boolean result = validateAuthorizationCode(code); // here you validate the code
if (result) {
JOptionPane.showMessageDialog(null, "Logged in!" );
} else {
JOptionPane.showMessageDialog(null, "Wrong code!" );
}
} else {
noticeWrongNumber(newPhoneNumber); // tell him the number is wrong, please reinput.
}

How to return properly in if else and avoid "void" for errors about return

I am having a hard time how to return into specific variable or how to return without getting any error base on my program.
class Facebook {
public static void main(String[]args){
String user = JOptionPane.showInputDialog(null,"Enter Username: ");
String pass = JOptionPane.showInputDialog(null,"Enter Password: ");
if(user.equals("jas")&&(pass.equals("bsit"))){
JOptionPane.showMessageDialog(null,"Welcome "+ user);
Selection Class = new Selection();
Selection.Selection1();
}
else if (!user.equals("jas")||(!pass.equals("bsit"))) {
JOptionPane.showMessageDialog(null,
"Invalid Username or Password",
"Wrong Authentication",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
}
class Selection{
public Selection1(){
try{
String select = JOptionPane.showInputDialog("[1]Home\n[2]Profile\n[3]Logout");
int numbers = Integer.parseInt(select);
if (numbers == 1){
JOptionPane.showMessageDialog(null,"Mang Tani: Lumakas ang hanging amihan halos nilipad ang mga bubong ng mga bahay\n\nJessica Soho: Isang sikat na pagkain sa davao inubos ng kabataan \n\n Boying Remulla: Walang pasok dahil sa malakas na ulan\n#WalangPasok.");
return select;
}
else if (numbers == 2){
JOptionPane.showMessageDialog(null,"Name: Ralph Jasper \n\n Age: 17 \n\n Address: Tierra Nevada, General Trias, Cavite");
}
else if (numbers == 3){
}
}
catch (NumberFormatException nfe){
JOptionPane.showMessageDialog(null,"Please input only numbers","Invalid Input",JOptionPane.ERROR_MESSAGE);
}
}
}
1) you want a method with a return value of a string
Replace
public Selection1(){
with
public String select()
2) all "paths" of a non-void method must result in a return statement. This does not mean a return statement needs to be inside any if else's, but you do need to return something within the method.
Suggestion: declare a String result = ""; outside of the try catch, return it after, outside of the catch, and assign it to your JOptionPane value in between like result = JOptionPane...
3) I'm assuming you actually want that value that's returned?
Selection selector = new Selection();
String selected = selector.select();
// TODO use that value
Notice: Java naming conventions -- methods are lowerCase, classes are UpperCase.

How to pass multiple parameters and a function and then execute function with parameters in Java 8?

We have this school project where we should make rent-a-car-like java app.
I wrote the following code that just takes some jsonObject properties, calls function depending on the action code and puts some things in jsonObject property. But I reaaally don't like this code repetition pattern...
if(action.equals("REGOPR")) {
// Register operator
String user = (String)jsonObject.get("username");
String pass = (String)jsonObject.get("password");
if(registerOperator(user, pass))
jsonObj.put("resp", "Operator successfully registered!");
else {
jsonObj.put("status", "fail");
jsonObj.put("resp", "Username already taken!");
}
} else if (action.equals("ADDVEH")) {
// Add vehicle
String manuf = (String)jsonObject.get("manufacturer");
String regis = (String)jsonObject.get("registration");
String licen =((String)jsonObject.get("license"));
if(addVehicle(manuf, regis, licen))
jsonObj.put("resp", "Successfully added vehicle!");
else {
jsonObj.put("status", "fail");
jsonObj.put("resp", "Vehicle alredy exists!");
}
} And fifteeen more else ifs with different "actions"...
What I would like to do instead is something like this
if(action.equals("REGOPR")){
awesomeMethod(registerOperator,
"Custom succesffull message",
"Fail message",
"username",
"password");
} else if(action.equals("ADDVEH")) {
awesomeMethod(addVehicle,
"Custom succesfull message 2",
"Fail message 2",
"manufacturer",
"registration",
"license");
}
So arbitrary number of Strings at the end and for each it should grab the value from json and just feed it into the given function.
Since the method signatures are incompatible (let's not try to change those), you would have to box into an array:
private void awesomeMethod(Predicate<String[]> func, String failMessage,
String succesMessage, String...arr) {
String[] args = new String[arr.length];
for(int i = 0; i < args.length; i++)
args[i] = (String) jsonObject.get(arr[i]);
if(func.test(args)) {
jsonObj.put("resp", succesMessage);
} else {
jsonObj.put("status", "fail");
jsonObj.put("resp", failMessage);
}
}
Then, when calling, you have to map array positions to arguments:
awesomeMethod(arr -> addVehicle(arr[0], arr[1], arr[2]),
"Custom succesfull message 2",
"Fail message 2",
"manufacturer",
"registration",
"license");
If you only have methods with few differing numbers of parameters, you could also consider making overloads for each number of parameters. That will avoid the array boxing, and make the call simpler.
You could also get rid of the if statements by using a map.

String.length() gives me a wrong value

Whenever I enter a password under 10 characters it gives me Password cannot exceed 10 characters.
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
String name = Name.getText();
String Username = uName.getText().toString();
String Pass1 = uPass.getPassword().toString();
String Confirm = uConfirm.getPassword().toString();
String Status = "OFFLINE";
int PassLen = Pass1.length();
if (Username.equals("") || Pass1.equals("") || Confirm.equals("") || name.equals(""))
{
JOptionPane.showMessageDialog(null, "You cannot leave any fields blank when creating an Account. Please Try Again");
}
else if ((uPass.getPassword().toString()).length()>10)
{
uPass.setText("");
uConfirm.setText("");
JOptionPane.showMessageDialog(null, "Password cannot exceed a maximum of 10 characters.");
}
else if (!Pass1.equals(Confirm))
{
uConfirm.setText("");
lblError1.setText("Passwords Do Not Match.");
lblError2.setText("Please re-enter your Password.");
}
else
{
try {
DB_Connect connect = new DB_Connect();
ResultSet rs = connect.queryTbl("SELECT * FROM ACOUNTS");
boolean AlreadyUser = false;
String User;
while (rs.next())
{
User = rs.getString("Username");
if(Username.equals(User))
{
AlreadyUser = true;
}
}
if (AlreadyUser==false)
{
connect.updateTbl("INSERT INTO NBUSER.ACCOUNTS (USERNAME,PASSWORD,STATUS,NAME)VALUES ('"+Username+"','"+Pass1+"','"+Status+"','"+name+"')");
JOptionPane.showMessageDialog(null, "Account Created Successfully !");
this.dispose();
new Topics().setVisible(true);
}
else
{
JOptionPane.showMessageDialog(null, "The Username you have selected already exists. Please select a different Username");
uPass.setText("");
uConfirm.setText("");
}
} catch (SQLException ex) {
Logger.getLogger(CreateAccount.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Since you're obviously using Swing, it is also very likely that you use a JPasswordField for your passwords. So let's see, what getPassword really does:
public char[] getPassword()
Returns the text contained in this TextComponent. If the underlying document is null, will give a NullPointerException. For stronger security, it is recommended that the returned character array be cleared after use by setting each character to zero.
Returns: the text
As you can see, it returns your password in a char[] and since this class doesn't override toString your call of uPass.getPassword().toString() results in something like:
[C#1d44bcfa
which is the result of calling Object#toString.
The length of this String is 11 and therefore larger then 10 and your else if block (else if ((uPass.getPassword().toString()).length()>10)) will be entered.
To fix that, call the String constructor String(char[]) like:
String Pass1 = new String(uPass.getPassword());
Please use this just as a "quick fix" for your current problem and try to find a way to use the originally returned char[]. As mentioned by the quoted JavaDoc it is recommened the "clean" the char array after using it, so the password won't be stored there anymore. By creating a String from the array, using new String(uPass.getPassword()), you're creating another object in the heap which contains the password and which also needs to be removed from there. So it would add more work for you.

JPasswordField returning some hash code converted into string type

My program takes user name and password authentication from user before initialising the program,
so i created a button login to which i associated ActionListener as show below
login.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
if(txtUserName.getText().equals("Suraj") && (txtPwd.getPassword().toString()).equals("s123")){
dispose();
TimeFrame tFrame = new TimeFrame(userName);
tFrame.setVisible(true);
tFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
tFrame.setLayout(new GridLayout());
} else {
JOptionPane.showMessageDialog(null,"User name or password don't match","Acces Denied", JOptionPane.ERROR_MESSAGE);
}
Now the problem that occurs is even if i enter correct password, program displays an error message
getPassword() returns a char[]. The toString() on it does not return the contents as a string as you assume.
Try new String(txtPwd.getPassword()).equals("s123").
However, there is a reason it is a char[] and not a String. Try looking up the security aspect of it in the javadoc.
Note: this should have been a comment but is way too long for this. Consider giving the upvotes to the answers in the linked thread
As already indicated by mKorbel there is a rather complete discussion in getText() vs getPassword() .
Further, read the Swing tutorial about JPasswordField which contains a nice example on how you should compare the password (by comparing char arrays, and not by converting the char array to a String) - small copy paste from the tutorial:
private static boolean isPasswordCorrect(char[] input) {
boolean isCorrect = true;
char[] correctPassword = { 'b', 'u', 'g', 'a', 'b', 'o', 'o' };
if (input.length != correctPassword.length) {
isCorrect = false;
} else {
isCorrect = Arrays.equals (input, correctPassword);
}
//Zero out the password.
Arrays.fill(correctPassword,'0');
return isCorrect;
}
The reason why you should compare char arrays is nicely explained by Hovercraft Full Of Eels in his answer in the linked SO question at the start of this answer.
I had the same problem:
private void loginActionPerformed(java.awt.event.ActionEvent evt) {
char[] pass = passwordField.getPassword();
String mypass = pass.toString();
String user = (String) combo.getSelectedItem();
try {
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:LoginDB";
con = DriverManager.getConnection(db);
st = con.createStatement();
String sql = "select * from Table2";
rs = st.executeQuery(sql);
while (rs.next()) {
String AdminNewID = rs.getString("AdminID");
String AdminNewPass = rs.getString("AdminPassword");
if ((user.equals(AdminNewID)) && pass.equals(AdminNewPass)) {
MyApp form = new MyApp();
form.setVisible(true);
} else {
this.res.setText(" Incorrect User Name or Password");
}
}
} catch (Exception ex) {
}
}

Categories