getting text from password field - java

Hello I am trying to create a login form in java netbeans IDE. My aim is to create multiple user ID's and their respective passwords. I have given textfields to userID and passwordField for passwords to get the values but the problem is i want to get the text from the password field and i am unable to get it its showing some error i think there is some problem with syntax my research is as follows can there be any solution? Need your help
private void lb_loginMouseClicked(java.awt.event.MouseEvent evt) {
DBUtil util = new DBUtil();
String value1=tb_uid.getText();
String value2=tb_pwd.getPassword();
String user1="";
String pass1="";
try {
Connection con = util.getConnection();
PreparedStatement stmt = con.prepareStatement("SELECT * FROM login where username='"+value1+"' && password='"+value2+"'");
ResultSet res = stmt.executeQuery();
res = stmt.executeQuery();
while (res.next()) {
user1 = res.getString("username");
pass1 = res.getString("password");
}
if (value1.equals(user1) && value2.equals(pass1)) {
JOptionPane.showMessageDialog(this,"correct");
}
else{
JOptionPane.showMessageDialog(this,"Incorrect login or password","Error",JOptionPane.ERROR_MESSAGE);
}
JOptionPane.showMessageDialog(null, "COMMITED SUCCESSFULLY!");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}

String pwd = new String(jPasswordField1.getPassword());
Option 1:
jTextField1.setText(""+pwd);
Option 2:
System.out.println(""+pwd);

Use this code:
String password = String.valueOf(jPasswordField.getPassword());
The JPasswordField is encrypted but if you use String.valueOf it will converted Char to String.

value2 is char array so doing String concatenation would result in the String representation of the array rather then the String content itself ending up in the SQL. You could replace
PreparedStatement stmt = con.prepareStatement("SELECT * FROM login where username='"+value1+"' && password='"+value2+"'");
with
PreparedStatement stmt = con.prepareStatement("SELECT * FROM login where username='"+value1+"' AND password='" + new String(value2) + "'");
Similarly
if (value1.equals(user1) && value2.equals(pass1)) {
would need to be
if (value1.equals(user1) && pass1.equals(new String(value2)) {
Better use the PreparedStatement placeholders however, to protect against SQL injection attack:
PreparedStatement stmt = con.prepareStatement("SELECT * FROM login where username=? AND password=?);
stmt.setString(1, value1);
stmt.setString(2, new String(value2));
Note: This is not a secure way do to a password lookup, a hashed comparison would be relatively safer.

From http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#equals%28java.lang.Object%29:
equals
public boolean equals(Object anObject)
Compares this string to the specified object. The result is true if
and only if the argument is not null and is a String object that
represents the same sequence of characters as this object.
Your code:
char[] value2=tb_pwd.getPassword();
...
String pass1="";
...
...&& value2.equals(pass1)...
Seems like you'd want to convert your char array into String then retry the conversion. If you're still getting an error please post it along with relevant input so we can see what is being received.

You want to convert your char[] to a String. When you envoke tb_pwd.getPassword() a char[] (character array) is returned. If you want to compare this password you must convert it to a String, and for this you can use this method:
String final_pass = "";
for(char x : passwordAsChar[]) {
final_pass += x;
}
As for comparing passwords in databases you should never store them in plain-text, unencrypted. You could store an MD5 string in your database, and the convert your password inputted by the user to a String, and then envoke the following method on it. Then compare the returned String with the one from the database. If they match, the user has entered a correct password.
Example:
char[] pass = tb_pwd.getPassword();
String final_pass = "";
for (char x : pass) {
final_pass += x;
}
String md5_encrypted_pass_userInput = encrypt(final_pass);
if (md5_encrypted_pass.equals(pass1)) { /* pass1 = the password from the database */
// Correct password
}
A method to use for encrypting Strings to MD5 is:
public static final String encrypt(String md5) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(md5.getBytes());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {}
return null;
}

Related

usernames and passwords are not matched and program is not moving further

try {
String pass = tf2.getPassword().toString();
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/javaproject", "root", "noor1032");
PreparedStatement myStat = myConn.prepareStatement("select*from user_info where username=? and password=?");
myStat.setString(1, tf1.getText());
myStat.setString(2, pass);
ResultSet Rs = myStat.executeQuery();
if (Rs.next()) {
f.dispose();
new sharepage();
} else {
JOptionPane.showMessageDialog(f, "Invalid username or password", "Alert", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception f) {
f.printStackTrace();
}
this is what i have written in code....i want that program should match both username and password and then move forward......But this is not happening....In database i have usernames with corresponding passwords. Help me please!!!
Replace
String pass = tf2.getPassword().toString();
with
String pass = new String(tf2.getPassword());
Why?
JPasswordField#getPassword() returns char[], and char[]#toString() does not return a new String containing the characters from the char array. Instead it returns something like "[C#54bedef2".
The correct way of converting a char[] cc into a String is new String(cc)
Change
myStat.setString(1, tf1.getText());
to
myStat.setString(1, tf1.getText().toString());
getText() returns Editable object and not String.

Java JDBC - User registration & login

I have 3 questions regarding my code below used for user registration.
1) How can I prevent users from registering themselves providing empty value in the username and password area?
2) I wonder if it's a good practice to both dispose & run the form again in case user credentials already exist in database. Is there any other way to go back to the main screen?
3) My programs runs correctly but there is a warning message in a line like "The method getText() from the type JPasswordField is deprecated". What does that mean exactly?
Code:
public void actionPerformed(ActionEvent arg0) {
try
{
String userID = userIDinput.getText();
String pass = passwordField.getText();
String myDriver = "com.mysql.jdbc.Driver"; //jdbc driver loaded
String myUrl = "jdbc:mysql://localhost:3306/masterdata_db?autoReconnect=true&useSSL=false";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
Statement st = conn.createStatement();
ResultSet resultSet;
String check = "SELECT Username FROM userregistration WHERE Username = '"+userID+"' ";
resultSet = st.executeQuery(check);
if(!resultSet.next()){
String sql = "INSERT INTO userregistration"
+ "(Username, Password) VALUES"
+ "(?,?)";
PreparedStatement pSt=conn.prepareStatement(sql);
pSt.setString(1, userID);
pSt.setString(2, pass);
pSt.executeUpdate();
conn.close();
}
else {
JOptionPane.showMessageDialog(frame, "USER ALREADY EXISTS. TRY ANOTHER ONE!", "Inane error",JOptionPane.ERROR_MESSAGE);
dispose();
new Login().setVisible(true);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
1)
if(userID.trim().isEmpty())//trim removes whitespaces
{
throw new SomeKindOfException();
//or just ...
return;
}
See this question.
2) Just remove the dispose and new Login(). JOptionPane will automatically "return to your main screen".
3) You should use password-fields like this:
JPasswordField passwordField = new JPasswordField();
char[] chars = passwordField.getPassword();
String pwd = new String(chars);
for (int i=0; i<chars.length; i++) chars[i] = ’x’; //overwrite password when done for more security
See How to Use Password Fields for more information.
The JPasswordField uses char[] instead of String, because Strings are immutable.
For more information see this question.

Converting plaintext passwords to bycrypt in MySQL and/or java

I inherited a project where the passwords are in plaintext in a table in the db. If I was converting to MD5 I'd just do something like
UPDATE users SET encrypted_password = MD5(password);
I'm using the java BCrypt class instead of MD5. The table has ~3 million users. Is there a optimal way to bcrypt each plaintext password into the new 'encrypted_password' column.
The only way I can think of is to loop through a ResultSet of each user, SELECT the plaintext password, bcrypt it, and then UPDATE the row. Something tells me this will take half an eternity. Anything quicker?
I think it might be the only way, and it did take forever, but I ended up just writing a simple class to iterate through each row and BCrypt the plaintext password and store it. Just for sanity, I checked if the match was good after BCrypting: I never got any mismatches. The Encryption class is just a fragment of an actual class I'm using with a lot of other encryption methods, I just included the relevant methods for clarity. If it helps anyone, here's the code:
public class Bcrypter {
public static void main(String args []) {
int lower = Integer.parseInt(args[0]);
int upper = Integer.parseInt(args[1]);
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
int row = 0;
try {
conn = Database.getConnection();
pstmt = conn.prepareStatement("SELECT id, user_pass, user_pass_bcrypt FROM users ORDER BY id LIMIT ?, ?",
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
pstmt.setInt(1, lower);
pstmt.setInt(2, upper);
rs = pstmt.executeQuery();
while (rs.next()) {
String user_pass = rs.getString("user_pass");
String user_pass_encrypted = Encryption.encrypt(user_pass);
if (Encryption.isMatch(user_pass, user_pass_encrypted)) {
rs.updateString("user_pass_bcrypt", user_pass_encrypted);
rs.updateRow();
if (++row % 10000 == 0) {
System.out.println(row);
}
} else {
System.out.println("Mismatch " + user_pass);
}
}
System.out.print("DONE");
} catch (SQLException e) {
e.printStackTrace();
System.out.print(e);
} finally {
Database.closeConnection(conn, pstmt, rs);
}
}
}
public final class Encryption {
private Encryption() {
// can't instantiate
}
/**
* Encrypts a password. The gensalt() method's default param is
* 10 but it's lowered here, assuming better performance.
*/
public static String encrypt (String plainPassword) {
return BCrypt.hashpw(plainPassword, BCrypt.gensalt(5));
}
/**
* Checks whether a plaintext password matches one that has been
* hashed previously
*/
public static Boolean isMatch(String plainPassword, String hashedPassword) {
return (BCrypt.checkpw(plainPassword, hashedPassword));
}
}

Encrypting password causes MySQL unknown column in 'where clause' [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
OK so I am trying to create user authentication for a little Java project of mine and I've run into a bit of a road block.
I have a table called user_info with 3 columns; id, user and password.
I realized that I should probably have some form of encryption, so I used Java's MessageDigest to encrypt the password with SHA1. Since I don't yet have a website for people to register (and have PHP enter the encrypted PW into the database), I simply encrypted a test password and replaced the unencrypted password in the database with the encrypted one.
For example, a user with username test and password test has an encrypted password of:
895df4f75b316de68d167ed2e83adb0bedbbde17
So my database has an entry with id 0, user test and password 895df4f75b316de68d167ed2e83adb0bedbbde17.
Now my Java code to check if the person provided valid details had no issue until I started using encrypted passwords.
Here is the login code for my Java application:
public int doLogin(String username, String pass) {
EncryptionHandler e = new EncryptionHandler();
String userToLogIn = username;
String userToLogInPassword = pass;
try {
String fixedUser = prepString(userToLogIn);
String fixedPass = e.doEncryptPassword(prepString(userToLogInPassword));
System.out.println(fixedPass);
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM `user_info` WHERE `user` = " + fixedUser + " AND `password` = " + fixedPass);
if (rs.next()) {
//System.out.println("ID: " + rs.getString(1) + ", USER: " + rs.getString(2) + ", PASSWORD: " + rs.getString(3));
return 1;
} else {
System.out.println("Username or password is invalid!");
return 0;
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
}
}
return 0;
}
private String prepString(String s) {
return new StringBuilder().append("'").append(s).append("'").toString();
}
and in case it's needed, my encryption method:
public String doEncryptPassword(String s) {
MessageDigest sha1;
try {
sha1 = MessageDigest.getInstance("SHA1");
byte[] digest = sha1.digest((s).getBytes());
return bytes2String(digest);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return s;
}
private static String bytes2String(byte[] bytes) {
StringBuilder string = new StringBuilder();
for (byte b : bytes) {
String hexString = Integer.toHexString(0x00FF & b);
string.append(hexString.length() == 1 ? "0" + hexString : hexString);
}
return string.toString();
}
Again, using unencrypted passwords works just fine, but as soon as I encrypt the password I get the unknown column error. In this example (user test, password test), passing the unencrypted password receives no error, but using the encrypted password 895df4f75b316de68d167ed2e83adb0bedbbde17 provides me the error:
Unknown column '895df4f75b316de68d167ed2e83adb0bedbbde17' in 'where clause'
Ignoring that this isn't encryption, you have invalid SQL because of quoting problems. As #Leigh notes in the comments, you put quotes at the beginning and end of your password string ... then hash it. Your quotes are now dearly departed.
Of course you should never create SQL like this in the first place. Use prepared statements -> Oracle Prepared Statements Tutorial
Get rid of any of your own home-grown string quoting then simply do:
String sqlString = "SELECT * FROM user_info WHERE user = ? AND password = ?";
PreparedStatement ps = con.prepareStatement(sqlString);
ps.setString(1, username);
ps.setString(2, hashedPassword);
ResultSet rs = ps.executeQuery();
You need to do your prepString thingy as well for the password:
String fixedPass = prepString(e.doEncryptPassword(userToLogInPassword));
But it isn't a good idea to build statements this way.
Use prepared statements.

Hashed passwords updated through JDBC become corrupt. (More of encoding problem than hashing)

I've tried the following with MySQL UTF-8 and Latin-1, to no avail.
I hash my passwords (in this case toSecurify) using SHA-1 like so:
if(toSecurify == null) {
throw new Exception("toSecurifyString must not be null");
}
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
byte[] sha1HashBytes = new byte[40];
messageDigest.update(toSecurify.getBytes(), 0, toSecurify.length());
sha1HashBytes = messageDigest.digest();
return new String(sha1HashBytes, "UTF-8");
} catch(NoSuchAlgorithmException nsae) {
throw new Exception("Hash algorithm not supported.");
} catch(UnsupportedEncodingException uee) {
throw new Exception("Encoding not supported.");
}
Then I store this in the mysql database password column.
Now here's the tricky part I can query the db kind of like:
Is there any record with
username=<insertUserName> and password = thatHashFunctionUpThere(<insertPassword>);
This works great.
But now, updating records looks something like this:
String userName = someJdbcStuffToGetUsername();
String password = someJdbcStuffToGetPassword();
update(userName, password);
The password has now changed! This corrupts the passwords.
It's like on the way out (when querying for it) it gets corrupted, but never on the way in.
I say this because inserts and queries work great, but when I get the value out then set it again, it corrupts it, so it must be on the way out.
Does anyone have any thoughts?
Where on the way out should I look for encoding issues?
Thanks in advance guys!
There's a flaw in your code.
return new String(sha1HashBytes, "UTF-8");
You shouldn't be treating the bytes as characters. You should in fact convert every byte to a 2-character hexstring. E.g.
StringBuilder hex = new StringBuilder(sha1HashBytes.length * 2);
for (byte b : sha1HashBytes) {
if ((b & 0xff) < 0x10) hex.append("0");
hex.append(Integer.toHexString(b & 0xff));
}
return hex.toString();
But, better is to just use MySQL's own SHA1() function. On INSERT do:
String sql = "INSERT INTO user (username, password) VALUES (?, SHA1(?))";
// ...
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(username);
preparedStatement.setString(password); // This one should be unhashed!!
int affectedRows = preparedStatement.executeUpdate();
// ...
and on UPDATE:
String sql = "UPDATE user SET username = ?, password = SHA1(?) WHERE id = ?";
// ...
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(username);
preparedStatement.setString(password); // This one should be unhashed!!
preparedStatement.setLong(id);
int affectedRows = preparedStatement.executeUpdate();
// ...
and on SELECT:
String sql = "SELECT * FROM user WHERE username = ? AND password = SHA1(?)";
// ...
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(username);
preparedStatement.setString(password); // This one should be unhashed!!
resultSet = preparedStatement.executeQuery();
// ...
See also:
Using prepared statements

Categories