unable to match password field in java with oracle database - java

I am trying to build a simple login form using Swing in Java. I created a Sample form with two fields.
usernamefield of type TextField
passfield of type PasswordField
Now I have a database and in that a login table which has following structure.
username | password
----------------------
abcd | xyz
Also I created a connection to database. and I am able to access table data by using ResultSet.
I made an object of database connection called conn.
I know that password is stored in the form of char array.
so when I try to match password by using following code it does not work.
if(usernamefield.getText() == conn.username && passfield.getPassword().toString == conn.password) {
system.out.println("Correct");
}else {
system.out.println("Incorrect");
}
Above code always go to else block.
I also noticed that passfield.getPassword() prints the correct password while passfield.getPassword().toString prints some random characters like [C#76dab03c
How to resolve it?

Use equals instead of == and it should work. Never use == on strings, it hardly ever produces the result you expect.
I think the more serious issue with your code is that you're storing passwords in plain text. That is a huge security risk. You should look into password hashing algorithms, for instance bcrypt.

You must compare string with .equals(), not ==, but you're doing this wrong anyway. The password should be hashed at the database, and you should be passing what the user entered to the database and having it do the matching, via a WHERE clause using the appropriate hash function. In other words, ask the database to fetch the user row with this username and password.

Related

Trying to get sql query parameter and automate script

I am using selenium and java.
Every time when I execute my test it has to create new log in credentials.
I enter usernames (every time it is created randomly)
This is my method to create a unique username:
String username=’’ ’’ +(int)(Math.random()*Integer.MAX_VALUE);
String emailID=”USER”+username+”#gmail.com”;
driver.findElement(by.id(“userNameID)).sendKeys(emailID);
system.out.println(emailID);
It creates a unique username.
After it will ask for verification code, it is coming from DB and I have to pass it in “verification textbox”.
I have my JDBC Connections,
Usually when I already know my username
I use:
String query=”Select SecretCode from createlogincode where
username=qacustomer#gmail.com”;
String secretCode=rs.getString(1);
System.out.println(“Verification Code is ”+secretCode);
driver.findElement(by.id(“secretcode”)).sendKeys(secretCode);
and this methods works perfectly.
But with creating random usernames, I am not able to write a correct query to pass and get verification code. Is there is any method to store the new username then pass it into the query?
I was doing:
String query=”Select SecretCode from createlogincode where username=
+emailID”;
but this is absolutely incorrect.

Hibernate HQL injection example

Yesterday searching through some repositories on Github I found some interesting stuff: one Java project (I won't mention the name of the repository but I've already notified the owner of it) contained a bad handling of HQL queries which could lead to SQL/HQL injections. The code was the following: (note that username and password come from the user)
Query query = session.createQuery("from Client where username = '" + username + "'");
List clients = query.list();
Client client = (Client) clients.get(0);
if (!validPassword(client.getPassword(), password)) {
return false;
}
//client is authenticated....
I think it is obvious that this query is injectable. I don't really know how this vulnerable query could be exploited because even if we inject the username, the
password is still checked. The database used was MySql (if it helps).
So my question is: how could this be exploited?
Even though HQL is more restrictive than SQL for injections, it can still be exploited.
Some example injections are explained at https://blog.h3xstream.com/2014/02/hql-for-pentesters.html
A similar question to this one has been asked already before at https://security.stackexchange.com/questions/24265/hql-injection-example
The answer to this question explains how characters of a password (hash) could be scanned. e.g. if for an Oracle database the value of username is:
admin' AND SUBSTR(password, 0, 1) = 'A
Then if
the first character of the password (hash) is not 'A' -> the clients List is empty and the clients.get(0) method call throws an IndexOutOfBoundsException
the first character of the password (hash) is 'A', but the provided password is false -> the user is not authenticated
the first character of the password (hash) is 'A' and the provided password is correct -> the user is authenticated
A hacker can repeat the query for each x and z in
SUBSTR(password, x, x + 1) = z
in the query above until the outcome is always case 2. where the user is not authenticated. This way he can find out the password hash for the user admin and may be able to crack his password.
Other exploits are possible, I am not going to list all of them...
Yes so...once you had start hibernate session, You can fetch data using query. Now you have written query for Client table.
For ex,
username = "ABC"
1) Your query from Client where username = 'ABC' will fetch data from Client whoes username is exact ABC.
If it found multiple same Username, it also return all.
2) It is going to store in list. 0 or more record will store in list.
3) Then whatever records came, it fetch only first record using
Client client = (Client) clients.get(0);
4) it check with client object record password with your expected password that may be suppose to save in some variable via method calling.
5) if it won't match then it return with false boolean flag otherwise code will go ahead with authenticated client execution.
Hope you got your answer.

Retrieve a Key from a properties file JAVA TOMCAT

so I'd like to know if it's possible to retrieve a key instead of a value from a properties object. I researched it but only came up with examples that list all of the keys. Is there a way to retrieve the key without having to use a loop to filter through all of them to get what I need?
Basically what I have is a login that stores the login info in a properties file where the user name is the key and the value is the password
pass = propertiesObj.getProperty(username);
How would I retrieve the username (the key) from the properties file so I can test if that is the same as what the user entered? I'm just looking for ideas on how to accomplish this, the properties object doesn't have anything to retrieve a key based off a value.
Thanks!
Given the use case you describe I can see no application for retrieving the username from looking it up by password.
The username as entered by the user will not return a password (or rather null) as long as there is not a key with that username. If however the entered username (the key) returns a password which is the same as the password entered by the user, there is a match and you can be sure the key is the same as what the user entered.
Looking up whether a username (key) exists is easy:
String username = "heresjohnny";
boolean isValidUsername = props.keySet().contains(username);
Properties extends Hashtable. Use the keySet method to get the keys.
If you want to fetch keys for values, then create a new HashMap with the keys and values swapped - by iterating through the keys, pulling out the values and add them to the new HashMap.

What does this methods do?

I'm new to connecting Java to SQL Server but hopefully I manage to connect them successfully through helps of various tutorials. But there are these methods and syntax that I couldn't explain for myself.
1.
Connection conn=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=login_DB;integratedSecurity=true");
Regarding the code above, what does integratedSecurity=true do?
2.
String user = rss.getString(1);
String pass = rss.getString(2);
Does the parameter inside getString(1) and getString(2) pertains to the column in the Database? And also, how does the ResultSet affects the getString()?
3.
while(rss.next()){
String user = rss.getString(1);
String pass = rss.getString(2);
if(usernameTF.getText().trim().equals(user)&&passwordTF.getText().trim().equals( pass)){
count = 1;
}//if success
}//while
Lastly, at least for now, does the while(rss.next()) method simply means that while there is a row in my table?
I know my code is a bad practice. But I am really trying my best to make it better.
Integrated Security = true/SSPI : the current Windows account credentials are used for authentication.
Integrated Security = False : User ID and Password are specified in the connection String.
rs.getString(1) - get 1 return column from your select statement.
Select x,y,z from table; rs.getString(1) gives x column result for particular row.
Your query returning n number row ,each time rs.next() check is there row available after current row.
Difference between Integrated Security = True and Integrated Security = SSPI
Yes the number refers to the column number, or you can pass a String as the column name to pull data.
Yes, whilst there is data in your ResultSet, for each iteration it will move the cursor to the next row of data available. Where you can access columns specifically using the syntax from part 2 of your question.
Hope this is useful.
According to Microsoft they are the same thing.
When false, User ID and Password are specified in the connection. When true, the current Windows account credentials are used for authentication.
Recognized values are true, false, yes, no, and sspi (strongly recommended), which is equivalent to true.
There however is a difference between them according to the comment below:
True ignores User Id and Password if provided and uses those of the running process, SSPI it will use them if provided which is why MS prefers this.
They are equivalent in that they use the same security mechanism to authenticate but that is it.
refer this link...!

Alter user password via jdbc. Problems with passes containing question marks

I have a problem with altering a users password when the password contains a question mark char. I do not encounter this problem with any other char so far, it seems specific to the question mark char.
If i alter a users password in sqlplus using the following sql:
Alter user Stephen identifed by "NewPassword?" REPLACE "OldPassword";
Then it changes the pass successfully and I can login using the new pass 'NewPassword?'.
However if I execute the same SQL via jdbc:
final String query = "ALTER user Stephen identified by \"NewPassword?\" REPLACE \"OldPassword\"";
stmt.executeUpdate(query);
I then cannot log in using the pass 'NewPassword?'.
Checking the hashcodes for the password when entered via sqlplus and jdbc show that they are different.
Somehow when I run the statement in jdbc it is entering something other than 'NewPassword?'.
I don't seem to have any problems with the following passwords:
NewPassword, NewPassword\, NewPassword'. It just seems to be the question mark that is causing problems.
Debugging shows the code point (dec) is 63 for the question mark so it doesn't look like its being changed midway.
Does anyone have any idea what could be causing this behaviour?
I'm at a loss at the moment, I'm considering preventing passes with question marks to bypass this problem for now.
To use JDBC to change the password of an Oracle user you need to do two things:
put the password directly in the SQL string (bind parameters cannot be used),
disable escape processing.
You can't use bind variables because the username and password are not sent to the database as single-quoted strings.
The ? in the SQL string is being taken as a bind variable placeholder, and because of this the SQL string is getting mangled at some point by Oracle JDBC. Disabling escape processing on the statement stops this from happening. Try:
Statement s = conn.createStatement();
s.setEscapeProcessing(false);
s.executeUpdate("ALTER user Stephen identified by \"newPassword?\" replace \"oldPassword\"");
If you are setting the password programmatically, your code should also ensure that the new and old passwords do not contain any " characters, to avoid SQL injection.
Try implementing it using a PreparedStatement and see if you get the same problem. Question marks are used in PreparedStatements as placeholders, so maybe the JDBC driver is getting confused. It shouldn't, but might be worth checking.
PreparedStatement p = conn.prepareStatement("ALTER user Stephen identified by ? replace ?");
p.setString(1, "NewPassword?");
p.setString(2, "OldPassword");
p.execute();
If this works then it's probably a bug in the driver.

Categories